.net core 读取配置文件

 1   /// <summary>
 2     /// 读取配置信息
 3     /// </summary>
 4     public class Zconfig
 5     {
 6         #region 读取配置信息
 7         /// <summary>
 8         /// 读取配置信息
 9         /// </summary>
10         /// <param name="name">key</param>
11         /// <returns></returns>
12         public static string Getconfig(string name)
13         {
14             IConfiguration config = new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }).Build();
15             var appconfig = new ServiceCollection()
16             .AddOptions()
17             .Configure<SiteConfig>(config.GetSection("SiteConfig"))
18             .BuildServiceProvider()
19             .GetService<IOptions<SiteConfig>>()
20             .Value;
21 
22             return appconfig.Configlist.FirstOrDefault(o => o.Name == name).Info;
23         } 
24         #endregion
25 
26     }
27 
28     #region 读取配置相关类
29     public class SiteConfig
30     {
31 
32         public List<SiteConfiglist> Configlist { get; set; }
33     }
34     public class SiteConfiglist
35     {
36         public string Name { get; set; }
37         public string Info { get; set; }
38     } 
39     #endregion

通过在appsettings.json配置节点,再通过以上方法 传入name的值读取info的值

原文地址:https://www.cnblogs.com/lyl6796910/p/6286358.html