基础
可以参考上一篇文章:C#使用YAML基础语法和心得
序列化/反序列化类
这是一个序列化和反序列化的源文件,可以直接用
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YamlDotNet.Serialization;
namespace YamlFile
{
/// <summary>
/// 序列化和反序列化yaml文件
/// </summary>
public class SerializeObject
{
static string _filePath = Directory.GetCurrentDirectory() + @"\Config\config.yaml";
static public void SetFilePath(string filePath)
{
_filePath = filePath;
}
static public void Serializer<T>(T obj) // 序列化操作
{
StreamWriter yamlWriter = File.CreateText(_filePath);
Serializer yamlSerializer = new Serializer();
yamlSerializer.Serialize(yamlWriter, obj);
yamlWriter.Close();
}
static public T Deserializer<T>() // 泛型反序列化操作
{
if (!File.Exists(_filePath))
{
throw new FileNotFoundException();
}
StreamReader yamlReader = File.OpenText(_filePath);
Deserializer yamlDeserializer = new Deserializer();
//读取持久化对象
T info = yamlDeserializer.Deserialize<T>(yamlReader);
yamlReader.Close();
return info;
}
}
}
示例
用上述序列化类,可以直接反序列化读取yaml文件,这里贴出一个示例,是把yaml用于配置文件的。
TestYaml m_curYaml;
private bool ReadYaml()
{
string path = AppDomain.CurrentDomain.BaseDirectory;
path += "modules\\Config\\Default.yaml";
m_curYaml = new TestYaml();
//加载所有程序信息
//如果配置文件不存在,使用new时的内置默认设置;
if (!System.IO.File.Exists(path))
{
MessageBox.Show("Error! Can not find config file!");
return false;
}
else
{
YamlFile.SerializeObject.SetFilePath(path);
m_curYaml = YamlFile.SerializeObject.Deserializer<TestYaml>();
}
return true;
}