C#读取配置文件内容
1.读取appsettings.json
1)配置文件
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "test": "xxxxxxx" }, "CustomSettings": { "test": "xxxxx" } }
2)读取方法
public class ConfigHelper { private static IConfigurationRoot builder; static ConfigHelper() { builder = new ConfigurationBuilder() .AddInMemoryCollection() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) .Build(); } public static string GetConnectionString(string connName) => builder.GetConnectionString(connName); public static string GetCustomSettings(string keyName) => builder.GetSection("CustomSettings")[keyName]; }
若出现 "ConfigurationBuilder”未包含“SetBasePath”的定义"的错误,解决方法如下: nuget 引用以下包 Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.FileExtensions Microsoft.Extensions.Configuration.Json Microsoft.Extensions.Configuration.Abstractions
3)调用
string test1= ConfigHelper.GetCustomSettings("test") string test2= ConfigHelper.GetConnectionString("test")
2.读取App.config文件中的appSettings信息
1)配置文件
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <appSettings> <add key="test" value="xxxx" /> </appSettings> </configuration>
2)读取方法
// 第一种 public static string GetAppsettings(string key) => ConfigurationManager.AppSettings[key]; GetAppsettings("test") // 第二种 private static System.Configuration.AppSettingsReader reader = new System.Configuration.AppSettingsReader(); reader.GetValue("test", typeof(String)).ToString()