我们一般创建的应用程序项目系统都会为它分配一个配置文件(应用程序项目一般为App.config)
默认内容如下
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
有时候我们需要在项目里面去读取配置文件的相关内容,这里就要使用到了
System.Configuration.dll
System.Configuration.ConfigurationManager类为我们提供了AppSettings和ConnectionStrings属性,可以让我们方便的读取到对应Section里面的内容
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Demo" connectionString="Data Source=xxx,xxx;database=xxx;User Id=xx;Password=xx;Max Pool Size=xx;Connect Timeout=5;" />
</connectionStrings>
<appSettings>
<add key="ServiceName" value="xx" />
<add key="ServiceDescription" value="xx" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
如我们需要读取appSetting里面的ServiceName 可以调用
ConfigurationManager.AppSettings.Get("ServiceName")
如何获取自定义内容呢
1、App.config中加入自定义Section
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="MySection" type="TestDemo.ConfigSectionHandler, TestDemo" />
</configSections>
<MySection>
<A>
<B name="1"></B>
</A>
</MySection>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
2、自定义ConfigSectionHandler类,实现System.Configuration.IConfigurationSectionHandler接口
namespace TestDemo
{
class ConfigSectionHandler : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
return section;
}
}
}
注意命名空间类名和App.config中type需要一致
3、主程序调用
static void Main(string[] args)
{
var obj = (System.Xml.XmlElement)System.Configuration.ConfigurationManager.GetSection("MySection");
Console.WriteLine(obj["A"]["B"].GetAttribute("name"));
System.Configuration.ConfigurationManager.RefreshSection("Mysection");
}
THE END