.net code 3.0 获取配置文件 json 和 config 中的值
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using System.IO;
方法:
/// <summary>
/// json配置文件读取
/// </summary>
/// <param name="configFileName"></param>
/// <param name="basePath"></param>
/// <returns></returns>
public static IConfigurationRoot GetJsonConfig(
string configFileName = "appsettings.json",
string basePath = "")
{
basePath = string.IsNullOrWhiteSpace(basePath) ? Directory.GetCurrentDirectory() : basePath;
var builder = new ConfigurationBuilder().
SetBasePath(basePath).
AddJsonFile(configFileName);
return builder.Build();
}
/// <summary>
/// xml配置文件读取
/// </summary>
/// <param name="configFileName"></param>
/// <param name="basePath"></param>
/// <returns></returns>
public static IConfigurationRoot GetXmlConfig(
string configFileName = "abc.config",
string basePath = "")
{
basePath = string.IsNullOrWhiteSpace(basePath) ? Directory.GetCurrentDirectory() : basePath;
var builder = new ConfigurationBuilder().
//SetBasePath(basePath).
AddXmlFile(b =>
{
b.Path = configFileName;
b.FileProvider = new PhysicalFileProvider(basePath);
});
return builder.Build();
}
调用:
var a = configXml.GetSection("Remotely:file:value").Value;
(Path)路径规则:"Remotely:file:value" 这串是路径path 用父子用:分开
例子
<?xml version="1.0" encoding="utf-8" ?>
<abc>
<Remotely>
<file value="https://baidu.com" />
</Remotely>
</abc>