C# 读写Yaml文件

一 项目引入YamlDotNet NuGet包

  1. 打开NuGet包管理界面

C# 读写Yaml文件_第1张图片

  1. 安装 YamlDotNet 包

C# 读写Yaml文件_第2张图片

二 定义Yaml文件对应的实体类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfigTool
{
    public class Configs
    {
      public List redisConfigs { get; set; }
        public Site site { get; set; }
    }
    public class RedisConfig
    {
        public List hostAndPorts { get; set; }
        public string tableName { get; set; }
        public int maxTotal { get; set; }
        public int maxIdle { get; set; }
        public long maxWaitMillis { get; set; }
        public long time { get; set; }
        public int pageCnt { get; set; }
      
    }
    public class ConfigHostAndPort
    {
        public string IP { get; set; }
        public int port { get; set; }
    }
}

三 读Yaml文件


            var configFromFile = new Object();

            Configs config = new Configs();
            using (TextReader reader = File.OpenText(path))
            {
                Deserializer deserializer = new Deserializer();
                config = deserializer.Deserialize(reader);
            }

四 写Yaml文件

 Configs configs = new Configs();
 
   YamlDotNet.Serialization.Serializer serializer = new YamlDotNet.Serialization.Serializer();
            StringWriter strWriter = new StringWriter();

            serializer.Serialize(strWriter, configs);
            serializer.Serialize(Console.Out, configs);
            
            using (TextWriter writer = File.CreateText(TXT_Path.Text))
            {
                writer.Write(strWriter.ToString());
            }
            

你可能感兴趣的:(.Net)