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上面改進的一個項目。
之前使用的時候,發現配置文件里面缺少字段的時候,會導致加載配置文件失敗。

浙公網安備 33010602011771號