Working with TOML

How to:

First, install a TOML parser like Tomlyn. Use your package manager:

dotnet add package Tomlyn

Next, parse a TOML file:

using Tomlyn;
using Tomlyn.Model;
using System;

var tomlContent = @"
name = 'Tom Preston-Werner'
dob = 1979-05-27T07:32:00Z";

var tomlTable = Toml.Parse(tomlContent).ToModel();

Console.WriteLine($"Owner: {tomlTable["owner"]["name"]}");
// Output:
// Owner: Tom Preston-Werner

Now, create and write TOML:

using Tomlyn;
using Tomlyn.Syntax;
using System;
using System.IO;

var doc = new DocumentSyntax
    Tables =
        new TableSyntax("owner")
            Items =
                { "name", "Tom Preston-Werner" },
                { "dob", "1979-05-27T07:32:00Z" }

var tomlString = doc.ToString();
File.WriteAllText("config.toml", tomlString);
Console.WriteLine("TOML written to config.toml");
// Output:
// TOML written to config.toml

Deep Dive:

TOML was created by Tom Preston-Werner, GitHub’s co-founder, around 2013 as a reaction to the limitations of existing formats like YAML and JSON in configuration settings. It’s specifically designed for configs with a strong emphasis on being straightforward and unambiguous.

Alternative config formats include YAML, JSON, and XML. Yet, TOML stands out for being more human-friendly, particularly for configuration files where editing by hand is common. JSON, while ubiquitous, is less readable for complex configs, and XML is verbose. YAML, though similar in readability, can get complicated with heavy use of whitespace and has security risks with certain content.

Implementation-wise, TOML focuses on mapping cleanly to a hash table, making data extraction predictable. With version 1.0.0 released, TOML solidified its spec, improving stability and tooling support.

See Also: