C#读写yaml文件

基础

可以参考上一篇文章: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;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值