Getting started

edit

Install the package

Add the Meziantou.Framework.Toml package to a project:

dotnet package add Meziantou.Framework.Toml

The package contains the source generator too: there is no other package to add. The examples of this documentation omit the using directives; see Namespaces for where each type lives.

Write and read an object

Declare the type that holds your data. A record, a class with properties, or a struct works:

public sealed record Person(string Name, int Age);

TomlSerializer.Serialize writes it as TOML, and TomlSerializer.Deserialize reads it back:

var toml = TomlSerializer.Serialize(new Person("Ada", 37));
Assert.Equal("""
    Name = "Ada"
    Age = 37

    """, toml);

var person = TomlSerializer.Deserialize<Person>(toml);
Assert.Equal(new Person("Ada", 37), person);
  • Each property is a key of the document. The keys keep the C# names (Name, Age) unless you set a naming policy; see Options.
  • The record has no parameterless constructor: the values are passed to its constructor, matched by name.

Read a configuration file

Deserialize and Serialize also take a Stream (UTF-8), a TextReader or a TextWriter:

using var stream = File.OpenRead("config.toml");
var config = TomlSerializer.Deserialize<ServerConfig>(stream);

using var writer = new StreamWriter("output.toml");
TomlSerializer.Serialize(writer, config);

Nested objects become tables, and collections of objects become arrays of tables. See Serializing objects for the types you can use.

Handle invalid input

A document that is not valid TOML, or does not match your type, throws a TomlException that gives the line and the column of the error. When invalid input is expected, for example a file written by a user, TryDeserialize returns false instead:

var toml = "Port = \"not a number\"";

var success = TomlSerializer.TryDeserialize<ServerConfig>(toml, out var config);
Assert.False(success); // Invalid input
Assert.Null(config);

See Handling errors.

Next steps