ZetCode

C# YAML

last modified November 15, 2026

In this article we show how to work with the YAML format in C# using the YamlDotNet library. We read YAML with the representation model, serialize and deserialize objects, map configuration files to classes, and convert YAML to JSON.

Understanding YAML

YAML (YAML Ain't Markup Language) is a human-friendly data-serialization format widely used for configuration files, data storage, and data exchange between programs. Structure is expressed with indentation instead of brackets or tags.

YAML natively supports three fundamental data types:

YAML files use the .yaml or .yml extension; .yaml is the officially recommended one. Comments start with #, and a single file can contain several documents separated by ---.

Using YAML in .NET

.NET has no built-in YAML support. The YamlDotNet library is the de-facto standard for parsing and emitting YAML in .NET. The examples in this article were tested with YamlDotNet 18.1 on .NET 10. Data files such as data.yaml are placed in the project directory, which is the working directory when the program is started with dotnet run.

We create a console project and add the package:

$ dotnet new console -o YamlDemo
$ cd YamlDemo
$ dotnet add package YamlDotNet

C# YamlStream

The YamlStream class loads YAML into a tree of nodes, the so-called representation model. Mappings become YamlMappingNode objects, sequences YamlSequenceNode objects, and scalars YamlScalarNode objects.

Program.cs
using YamlDotNet.RepresentationModel;

string doc = """
    cities:
      - Bratislava
      - Kosice
      - Trnava
      - Moldava
      - Trencin
    name: John Doe
    occupation: gardener
    """;

using var sr = new StringReader(doc);

var yaml = new YamlStream();
yaml.Load(sr);

var root = (YamlMappingNode) yaml.Documents[0].RootNode;

foreach (var e in root.Children)
{
    Console.WriteLine($"{e.Key} -> {e.Value}");
}

Console.WriteLine("------------------------------");

Console.WriteLine(root["name"]);
Console.WriteLine(root["occupation"]);

var cities = (YamlSequenceNode) root["cities"];

foreach (var city in cities)
{
    Console.WriteLine(city);
}

In the example, we read YAML from a string and walk the node tree.

string doc = """
    cities:
      - Bratislava
      - Kosice
      - Trnava
      - Moldava
      - Trencin
    name: John Doe
    occupation: gardener
    """;

The YAML data is defined in a raw string literal. The common leading whitespace is removed, so the YAML starts at column one.

using var sr = new StringReader(doc);

var yaml = new YamlStream();
yaml.Load(sr);

The Load method reads from any TextReader; here we wrap the string in a StringReader.

var root = (YamlMappingNode) yaml.Documents[0].RootNode;

A stream can hold several documents. We take the root node of the first document and cast it to a mapping node, because the document is a mapping of keys to values.

foreach (var e in root.Children)
{
    Console.WriteLine($"{e.Key} -> {e.Value}");
}

The Children property is a dictionary of key and value nodes. A sequence value is printed in YAML flow style, with square brackets.

var cities = (YamlSequenceNode) root["cities"];

foreach (var city in cities)
{
    Console.WriteLine(city);
}

The indexer looks up a child by its key. The cities value is a sequence node, which is enumerable.

$ dotnet run
cities -> [ Bratislava, Kosice, Trnava, Moldava, Trencin ]
name -> John Doe
occupation -> gardener
------------------------------
John Doe
gardener
Bratislava
Kosice
Trnava
Moldava
Trencin

YAML documents

YAML documents are separated with ---. The YamlStream loads all of them into its Documents collection.

data.yaml
name: Document 1
cities:
  - Bratislava
  - Kosice
  - Trnava
  - Moldava
  - Trencin
---
name: Document 2
companies:
  - Eset
  - Slovnaft
  - Duslo Sala
  - Matador Puchov

We have two documents in the YAML file.

Program.cs
using YamlDotNet.RepresentationModel;

using var sr = new StreamReader("data.yaml");

var yaml = new YamlStream();
yaml.Load(sr);

Console.WriteLine($"Number of documents: {yaml.Documents.Count}");

foreach (var doc in yaml.Documents)
{
    var root = (YamlMappingNode) doc.RootNode;

    foreach (var e in root.Children)
    {
        Console.WriteLine($"{e.Key}: {e.Value}");
    }

    Console.WriteLine("-------------------------------");
}

The program reads both documents and prints their keys and values.

using var sr = new StreamReader("data.yaml");

This time the YAML is read from a file through a StreamReader.

Console.WriteLine($"Number of documents: {yaml.Documents.Count}");

The Documents property is a list of YamlDocument objects.

foreach (var doc in yaml.Documents)
{
    var root = (YamlMappingNode) doc.RootNode;

We go over the documents and get the root mapping node of each.

$ dotnet run
Number of documents: 2
name: Document 1
cities: [ Bratislava, Kosice, Trnava, Moldava, Trencin ]
-------------------------------
name: Document 2
companies: [ Eset, Slovnaft, Duslo Sala, Matador Puchov ]
-------------------------------

Serialize data

Serializing is the process of transforming C# objects into YAML text. The serializer is created with the SerializerBuilder, which lets us configure it before calling Build.

Program.cs
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

List<User> users =
[
    new("John Doe", "gardener", 1200),
    new("Roger Roe", "driver", 1450),
    new("Valeria Smith", "teacher", 1780)
];

var serializer = new SerializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .Build();

string yaml = serializer.Serialize(users);
Console.WriteLine(yaml);

record User(string Name, string Occupation, int Salary);

The program transforms a list of User records into a YAML string.

var serializer = new SerializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .Build();

By default, the property names are written as they are, for example Name. The CamelCaseNamingConvention turns them into name, occupation, and salary. Other conventions include UnderscoredNamingConvention, HyphenatedNamingConvention, and LowerCaseNamingConvention.

string yaml = serializer.Serialize(users);

The Serialize method returns the YAML text. A list becomes a sequence and each record becomes a mapping.

$ dotnet run
- name: John Doe
  occupation: gardener
  salary: 1200
- name: Roger Roe
  occupation: driver
  salary: 1450
- name: Valeria Smith
  occupation: teacher
  salary: 1780

Deserialize data

Deserializing is the process of transforming YAML text into C# objects. The deserializer is created with the DeserializerBuilder.

users.yaml
- name: John Doe
  occupation: gardener
  salary: 1200
- name: Roger Roe
  occupation: driver
  salary: 1450
- name: Valeria Smith
  occupation: teacher
  salary: 1780

We have a list of users in the users.yaml file.

Program.cs
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

var deserializer = new DeserializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .Build();

using var sr = File.OpenText("users.yaml");
var users = deserializer.Deserialize<List<User>>(sr);

foreach (var user in users)
{
    Console.WriteLine(user);
}

Console.WriteLine($"Total salaries: {users.Sum(u => u.Salary)}");

class User
{
    public string Name { get; set; } = "";
    public string Occupation { get; set; } = "";
    public int Salary { get; set; }

    public override string ToString() => $"{Name}, {Occupation}, {Salary}";
}

The program reads the file and deserializes it into a list of User objects.

var deserializer = new DeserializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .Build();

The keys in the file are in camel case, so we configure the same naming convention as for serialization. Without it, the deserializer would look for Name keys and fail on name.

using var sr = File.OpenText("users.yaml");
var users = deserializer.Deserialize<List<User>>(sr);

The generic Deserialize method creates the objects and fills their properties. The number 1200 is converted to the int type of the Salary property.

Note that User is a class with a parameterless constructor and settable properties. YamlDotNet creates the object first and then sets the properties. A positional record such as record User(string Name, string Occupation, int Salary) can be serialized, but deserializing it fails with No parameterless constructor defined.

$ dotnet run
John Doe, gardener, 1200
Roger Roe, driver, 1450
Valeria Smith, teacher, 1780
Total salaries: 4430

Configuration file

YAML is popular for configuration files. In the next example, we map a nested configuration to a set of classes.

config.yaml
# application settings
app_name: Inventory
version: 2.1
debug: false

server:
  host: localhost
  port: 8080

database:
  provider: PostgreSQL
  connection_timeout: 30
  retry_count: 3

allowed_origins:
  - https://example.com
  - https://api.example.com

log_level: Information

The configuration contains a comment, scalars of different types, two nested mappings, and a sequence. The keys use underscores.

Program.cs
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

var deserializer = new DeserializerBuilder()
    .WithNamingConvention(UnderscoredNamingConvention.Instance)
    .IgnoreUnmatchedProperties()
    .Build();

string text = File.ReadAllText("config.yaml");
var config = deserializer.Deserialize<AppConfig>(text);

Console.WriteLine($"{config.AppName} {config.Version}, debug: {config.Debug}");
Console.WriteLine($"Listening on {config.Server.Host}:{config.Server.Port}");
Console.WriteLine($"Database: {config.Database.Provider}");
Console.WriteLine($"Timeout: {config.Database.ConnectionTimeout} s");
Console.WriteLine($"Retries: {config.Database.Retries}");
Console.WriteLine($"Origins: {string.Join(", ", config.AllowedOrigins)}");

class AppConfig
{
    public string AppName { get; set; } = "";
    public decimal Version { get; set; }
    public bool Debug { get; set; }
    public ServerConfig Server { get; set; } = new();
    public DatabaseConfig Database { get; set; } = new();
    public List<string> AllowedOrigins { get; set; } = [];
}

class ServerConfig
{
    public string Host { get; set; } = "";
    public int Port { get; set; }
}

class DatabaseConfig
{
    public string Provider { get; set; } = "";
    public int ConnectionTimeout { get; set; }

    [YamlMember(Alias = "retry_count")]
    public int Retries { get; set; }
}

The program loads the configuration into an AppConfig object.

var deserializer = new DeserializerBuilder()
    .WithNamingConvention(UnderscoredNamingConvention.Instance)
    .IgnoreUnmatchedProperties()
    .Build();

The UnderscoredNamingConvention maps app_name to the AppName property and connection_timeout to ConnectionTimeout. The IgnoreUnmatchedProperties call makes the deserializer skip keys that have no matching property; our classes have no property for log_level. Without this setting, the deserializer throws a YamlException for the first unknown key.

public ServerConfig Server { get; set; } = new();
public DatabaseConfig Database { get; set; } = new();
public List<string> AllowedOrigins { get; set; } = [];

Nested mappings are deserialized into nested objects and the sequence into a list of strings.

[YamlMember(Alias = "retry_count")]
public int Retries { get; set; }

The YamlMember attribute maps a key to a property whose name does not follow the naming convention. An alias is used as it is; the naming convention is not applied to it.

$ dotnet run
Inventory 2.1, debug: False
Listening on localhost:8080
Database: PostgreSQL
Timeout: 30 s
Retries: 3
Origins: https://example.com, https://api.example.com

Deserialize to dictionary

When we do not have classes for the data, we can deserialize YAML into dictionaries and lists.

Program.cs
using YamlDotNet.Serialization;

var deserializer = new DeserializerBuilder().Build();

string text = File.ReadAllText("config.yaml");
var data = deserializer.Deserialize<Dictionary<string, object>>(text);

foreach (var (key, value) in data)
{
    Console.WriteLine($"{key}: {value} ({value.GetType().Name})");
}

Console.WriteLine("------------------------------");

var server = (Dictionary<object, object>) data["server"];
Console.WriteLine($"port: {server["port"]}");

var origins = (List<object>) data["allowed_origins"];
Console.WriteLine($"first origin: {origins[0]}");

The program reads the config.yaml file from the previous section into a dictionary.

var data = deserializer.Deserialize<Dictionary<string, object>>(text);

The top-level mapping becomes a Dictionary<string, object>.

var server = (Dictionary<object, object>) data["server"];
Console.WriteLine($"port: {server["port"]}");

var origins = (List<object>) data["allowed_origins"];

Nested mappings become Dictionary<object, object> objects and sequences List<object> objects. The output shows that without target types, all scalars are deserialized as strings, including 2.1 and false.

$ dotnet run
app_name: Inventory (String)
version: 2.1 (String)
debug: false (String)
server: System.Collections.Generic.Dictionary`2[System.Object,System.Object] (Dictionary`2)
database: System.Collections.Generic.Dictionary`2[System.Object,System.Object] (Dictionary`2)
allowed_origins: System.Collections.Generic.List`1[System.Object] (List`1)
log_level: Information (String)
------------------------------
port: 8080
first origin: https://example.com

Convert YAML to JSON

The serializer can emit JSON instead of YAML. This lets us convert a YAML file to JSON without defining any classes.

Program.cs
using System.Text.Json;
using System.Text.Json.Nodes;
using YamlDotNet.Serialization;

var deserializer = new DeserializerBuilder()
    .WithAttemptingUnquotedStringTypeDeserialization()
    .Build();

var serializer = new SerializerBuilder()
    .JsonCompatible()
    .Build();

string yaml = File.ReadAllText("config.yaml");
object? data = deserializer.Deserialize(yaml);

string json = serializer.Serialize(data);

var node = JsonNode.Parse(json);
var options = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(node?.ToJsonString(options));

The program converts the configuration file to JSON.

var deserializer = new DeserializerBuilder()
    .WithAttemptingUnquotedStringTypeDeserialization()
    .Build();

With WithAttemptingUnquotedStringTypeDeserialization, the deserializer converts unquoted scalars to numbers and booleans where possible. Without it, every value would end up as a JSON string, for example "port": "8080".

var serializer = new SerializerBuilder()
    .JsonCompatible()
    .Build();

The JsonCompatible option makes the serializer produce JSON.

var node = JsonNode.Parse(json);
var options = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(node?.ToJsonString(options));

YamlDotNet writes the JSON on a single line. We parse it with System.Text.Json and write it indented; the successful parsing also confirms that the output is valid JSON.

$ dotnet run
{
  "app_name": "Inventory",
  "version": 2.1,
  "debug": false,
  "server": {
    "host": "localhost",
    "port": 8080
  },
  "database": {
    "provider": "PostgreSQL",
    "connection_timeout": 30,
    "retry_count": 3
  },
  "allowed_origins": [
    "https://example.com",
    "https://api.example.com"
  ],
  "log_level": "Information"
}

Source

YamlDotNet GitHub page
YamlDotNet documentation
YAML 1.2 specification

In this article we have worked with the YAML format in C# using the YamlDotNet library. We have read YAML with YamlStream, serialized and deserialized objects, loaded a configuration file, and converted YAML to JSON. See also the C# JSON and C# StreamReader articles.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.