【问题标题】:How to create a custom app.config with just one extra entry如何使用一个额外的条目创建自定义 app.config
【发布时间】:2017-05-18 14:26:44
【问题描述】:

我希望我的 app.config 文件类似于

<configSections>
    <section name ="RegCompany" type =""/>
</configSections>

<RegCompany>
<Company name="Tata Motors" code="Tata"/>
<SomethingElse url="someuri"/>
</RegCompany>

知道怎么做吗?我想通过我的代码获取这里定义的值。

【问题讨论】:

  • 问题不完整。您能否详细说明您要做什么。您可以在当前 App.config 或 Web.config 中使用 AppSettings 来获取额外的配置值
  • 我不想在我的代码中使用 appsettings。我想在 app.config 文件中添加一个 customConfig 部分,以便使用我的应用程序的开发人员可以轻松设置这些值。
  • 您放在这里的当前代码有什么问题?您在调试时遇到任何异常/错误?
  • 用谷歌搜索你写的字词"customConfig Section in app.config file",第一个结果链接到How to: Create Custom Configuration Sections Using ConfigurationSection
  • 此外,您的自定义配置部分看起来与这个重复的问题相同(带有答案!!):stackoverflow.com/questions/1316058/… 请花一点时间来查找类似问题。

标签: c# .net .net-4.5 app-config


【解决方案1】:

对于像这样的简单值,有一个比重复问题中的更简单的解决方案。

配置:

<configSections>
    <section name="RegCompany" type="System.Configuration.NameValueSectionHandler"/>
</configSections>

<RegCompany>
     <add key="CompanyName" value="Tata Motors" />
     <add key="CompanyCode" value="Tata" />
     <add key="CompanyUrl" value="example.com" />
</RegCompany>

代码:

var section = ConfigurationManager.GetSection("RegCompany") as NameValueCollection;
if (section == null) {
    throw new InvalidOperationException("Unknown company");
}

var company = section["CompanyName"];
var code = section["CompanyCode"];
var url = section["CompanyUrl"];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2011-11-21
    • 2011-06-23
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多