【发布时间】:2017-05-07 21:50:21
【问题描述】:
我会尽可能具体。我有上面的配置,我检索并使用它。我想要的是将“key”的关键字更改为“car”和“value ”到“品牌编号”。
这可能吗?
我尝试在更改关键字名称后检索值,但不能使用当前代码检索键/值。
<!-- Custom section in App.config file. -->
<configSections>
<section
name="CarMapping"
type="System.Configuration.AppSettingsSection" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<!-- Mapping the cars to specific brandNumber. -->
<CarMapping>
<add key="1" value="A"/>
<add key="2" value="B"/>
<add key="3" value="C"/>
<add key="4" value="A"/>
<add key="5" value="D" />
</CarMapping>
从 App.config 文件中获取键/值并将其存储到 Dictionary 的代码。
// Get the configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Get the appSettings section.
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("CarMapping");
// Get the settings collection (key/value pairs).
foreach (string key in appSettings.Settings.AllKeys)
{
string value = appSettings.Settings[key].Value;
string keyValue = appSettings.Settings[key].Key;
Console.WriteLine(appSettings.Settings[key].Key);
MyDectionary.Add(keyValue, value); }
这就是我想要的。请让我知道检索“汽车”和“品牌编号”的代码。提前谢谢你。
<!-- Mapping the cars to specific brandNumber. -->
<CarMapping>
<add car="1" brandNumber="A"/>
<add car="2" brandNumber="B"/>
<add car="3" brandNumber="C"/>
<add car="4" brandNumber="A"/>
<add car="5" brandNumber="D" />
</CarMapping>
【问题讨论】:
-
不清楚你到底想做什么。是否要更改自定义配置部分的格式?还是您想按原样阅读它,并在运行时将其翻译以在您的应用程序中使用?
-
我实际上并没有得到你想要达到的目标。这种类型的信息通常与配置文件无关。特别是当您需要更改映射时,您无法编写应用程序的配置文件。
-
@Thorsten 很好,您可以通过在自定义配置部分中包含这两种格式并从一种转换到另一种。但这不是一个很有用的方法。
-
@CodeCaster 但这与写入应用程序的设置不同。那是写入用户的设置。您不能依赖被允许写入应用程序的配置文件,因为普通应用程序没有写入 Program Files 文件夹所需的权限。这就是我的意思。
-
@Thorsten 好吧,我同意。
标签: c# app-config