Parse the YAML, then call Deserialize<Server>() on the server node.
dotnet add package OneYamlThe library targets .NET 8 and later; the example project uses .NET 10.
using OneYaml; using var doc = YamlDocument.Parse(""" server: host: example.test port: 8080 logging: level: info """); var section = doc.Root["server"]; var server = section.Deserialize<Server>() ?? throw new FormatException("No server"); Console.WriteLine( $"{server.Host}:{server.Port}"); record Server(string Host, int Port);
Unzip the example, then dotnet run.
example.test:8080The server key must exist: the indexer throws KeyNotFoundException if it’s missing. If server: is present but empty or set to null, Deserialize<Server>() returns null, and ?? throw turns that into a FormatException.
Variations
Read from a file. Save the YAML from the snippet as config.yaml in your working directory. Replace the YamlDocument.Parse call and its inline YAML with these two lines; the rest of the program still prints example.test:8080:
using var file = File.OpenRead("config.yaml"); using var doc = YamlDocument.Parse(file);
Read just one setting. Replace the server binding and its print line with this pointer lookup. A JSON Pointer is a slash-separated path to a node; this one reads an integer, not a record:
Console.WriteLine(doc.Get<int>("/server/port"));8080Related recipes
The short answer
To deserialize one section of a YAML file in C#, parse the document with YamlDocument.Parse, select the mapping with doc.Root["server"], then call Deserialize<Server>() on that node. The parser still reads the entire YAML document. Only the selected mapping is bound to your C# type, so sibling sections need to be valid YAML but don’t need corresponding properties or classes.
How do you read part of a YAML file without modeling the whole file?
Model the fields immediately inside the section: Host and Port in the example. Host maps to host and Port to port under the default camel-case naming policy. A class with those two properties works as well as the record; the record gives the example a constructor and properties in one line. OneYaml’s serializer guide explains record binding and naming options.
A selected node is not a separate file. If the section uses a YAML alias to refer to an anchor elsewhere in the document, OneYaml follows that alias during binding. Keep the document open while reading from its nodes; the returned record is the C# result, not a node handle. See reading and editing YAML nodes.
When should you read one YAML value instead of binding a class?
Use a scalar lookup like /server/port when you only need the port. Use Deserialize<Server>() when several fields belong together and you want a typed object to pass on. Use YamlSerializer.Deserialize<Config>(yaml) from the start instead when your C# model already represents the whole document. In that case Config is the shape of the root mapping and can include both server and logging if the application uses both.