Leggere file TOML in VB.NET con Tomlyn

Mattepuffo's logo
Leggere file TOML in VB.NET con Tomlyn

Leggere file TOML in VB.NET con Tomlyn

In questo articolo vediamo come leggere un file TOML in VB.NET usando Tomlyn.

E' solo una delle librerie disponibili per .NET, ma è quella più veloce e facile da usare.

Per installarla:

dotnet add package Tomlyn

Questo il file TOML:

title = "Test TOML"
version = "1.0.0"

[database]
host = "localhost"
port = 5432
username = "root"
password = "password"
databases = ["db_test"]
pool_size = 10
ssl_enabled = true

[server]
host = "0.0.0.0"
port = 8080
debug = false
allowed_hosts = ["*"]

[logging]
level = "INFO"
format = "%(asctime)s - %(levelname)s - %(message)s"
handlers = ["console", "file"]

[cache]
enabled = true
ttl = 3600
max_size = 1000

[features]
enable_api = true
rate_limit = 100

Qui sotto il codice:

Imports System
Imports System.IO
Imports Tomlyn
Imports Tomlyn.Model

Module Program
    Sub Main(args As String())
        Dim tomlText As String = File.ReadAllText("test.toml")
        Dim config As TomlTable = Toml.Parse(tomlText).ToModel()
        Dim title As String = CStr(config("title"))
        Dim version As String = CStr(config("version"))
        Dim db As TomlTable = CType(config("database"), TomlTable)
        Dim dbHost As String = CStr(db("host"))
        Dim dbPort As Long = CLng(db("port"))
        Dim dbUser As String = CStr(db("username"))
        Dim sslEnabled As Boolean = CBool(db("ssl_enabled"))
        Dim dbList As TomlArray = CType(db("databases"), TomlArray)
        Dim firstDatabase As String = CStr(dbList(0))
        
        Console.WriteLine($"Title: {title} v{version}")
        Console.WriteLine($"DB: {dbUser}@{dbHost}:{dbPort}, SSL={sslEnabled}, First DB={firstDatabase}")
        
        Dim server As TomlTable = CType(config("server"), TomlTable)
        Console.WriteLine($"Server: {server("host")}:{server("port")}")

        Dim logging As TomlTable = CType(config("logging"), TomlTable)
        Console.WriteLine($"Logging level: {logging("level")}")

        Dim features As TomlTable = CType(config("features"), TomlTable)
        Console.WriteLine($"API enabled: {features("enable_api")}, rate limit: {features("rate_limit")}")
    End Sub
End Module

Enjoy!


Condividi

Commentami!