C#读取和保存YAML配置文件

关于YAML的保存和读取,目前有YamlDotNet和SharpYaml两个库。
前面的试用过程中,发现SharpYaml在读取配置文件的时候有一点问题,目前更推荐使用YamlDotNet。

YamlDotNet

安装:

Install-Package YamlDotNet

保存配置文件:

var person = new Person
{
    Name = "Abe Lincoln",
    Age = 25,
    HeightInInches = 6f + 4f / 12f,
    Addresses = new Dictionary<string, Address>{
        { "home", new  Address() {
                Street = "2720  Sundown Lane",
                City = "Kentucketsville",
                State = "Calousiyorkida",
                Zip = "99978",
            }},
        { "work", new  Address() {
                Street = "1600 Pennsylvania Avenue NW",
                City = "Washington",
                State = "District of Columbia",
                Zip = "20500",
            }},
    }
};

var serializer = new SerializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .Build();
var yaml = serializer.Serialize(person);
File.WriteAllText("config.yaml",yaml);
System.Console.WriteLine(yaml);

读取配置文件:

var yaml = File.ReadAllText(filePath);
var deserializer = new DeserializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .Build();

var person = deserializer.Deserialize<Person>(yaml);

Console.WriteLine($"Name: {person.Name}");

foreach (var item in person.Addresses)
{
    Console.WriteLine(item.Key);
    Console.WriteLine(item.Value.Zip);
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public float HeightInInches { get; set; }
    public Dictionary<string, Address> Addresses { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

SharpYaml

Install-Package SharpYaml

SharpYaml说是在YamlDotNet上面改进的一个项目。
之前使用的时候,发现配置文件里面缺少字段的时候,会导致加载配置文件失败。

posted @ 2025-06-05 11:30  wzwyc  阅读(72)  评论(0)    收藏  举报