winform中使用yaml配置文件

1、引入nuget包

  • NetEscapades.Configuration.Yaml
  • Microsoft.Extensions.Configuration.Binder

  引入上面两个包

  

2、新增yaml文件

  可以新增到目录中,也可以放在根目录,我这边新增到了Conf文件夹中。

  创建一个Conf文件夹,然后里面创建一个myconfig.yaml文件。

  

   myconfig.yaml文件内容如下:(表示一个对象数组,具体yaml格式可以自行百度)

BuildPath:
 -
  key: Entity
  path: po
 -
  key: Dao
  path: dao

3、使用

  3.1、配置

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace CodeBuilder
{
    internal static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // To customize application configuration such as set high DPI settings or default font,
            // see https://aka.ms/applicationconfiguration.
            ApplicationConfiguration.Initialize();

            // 配置yaml读取路径
            var configBuilder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddYamlFile("Conf/myconfig.yaml");
            // 创建服务容器
            var services = new ServiceCollection();
            // 注册配置文件
            services.AddSingleton<IConfiguration>(configBuilder.Build());
        }
    }
}

  3.2、读取

using Microsoft.Extensions.Configuration;

namespace CodeBuilder.Service.Impl
{
    public class EntityFileService: IEntityFileService
    {
        private readonly IConfiguration _configuration;

        public EntityFileService(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public void BuildEntity()
        {
            // 获取配置生成的路径
            var buildPaths = _configuration.GetSection("BuildPath").Get<List<BuildPathConf>>();
        }
    }

    public class BuildPathConf
    {
        /// <summary>
        /// Key
        /// </summary>
        public string Key { set; get; }
        /// <summary>
        /// Path
        /// </summary>
        public string Path { set; get; }
    }
}

4、验证

  经过打断点调试,yaml文件中的数据已经被成功读取

  

 

posted @ 2023-06-03 22:52  关心千九  阅读(161)  评论(0编辑  收藏  举报