[英]Custom section in App.Config, ConfigurationManager stops working
我在 C# 中创建了一个控制台应用程序,它从 App.config 读取信息。 如果我在 appSettings 部分添加内容,我可以访问它们并且它可以工作,但是一旦我添加了一些自定义部分,我就无法从中读取任何内容。 我正在使用 ConfigurationManager,我有它的参考。 我的应用程序配置如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
我正在尝试访问这些信息:
string path = ConfigurationManager.AppSettings["path"];
var settings = ConfigurationManager.GetSection("ImageFormatsINeed");
当我没有ImageFormatsINeed部分时,我可以从 AppSettings 获取路径并且它正在工作。 但是一旦我添加了我的ImageFormatsINeed部分,一切都会停止工作。
现在我的问题是如何在 app.config 中添加自定义部分使其起作用,或者我应该从一些自定义 xml 文件或配置文件中读取我的 ImageInformation 吗?
您必须在 app.config 的顶部使用标签 < configSections >,对于这种情况,您应该使用类型AppSettingsSection
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ImageFormatsINeed" type="System.Configuration.AppSettingsSection" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="overwriteBackupFiles" value="False"/>
<add key="path" value="c:\temp"/>
</appSettings>
<ImageFormatsINeed>
<add key="type1" value="width=180&height=180"></add>
<add key="type2" value="width=220&height=220"></add>
<add key="type3" value="width=500&height=500"></add>
</ImageFormatsINeed>
</configuration>
然后在你的 C# 代码中:
NameValueCollection settings_section = ConfigurationManager.GetSection("ImageFormatsINeed") as NameValueCollection;
Console.WriteLine(settings_section["type1"]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.