我通常使用文本文件作为配置。但是这次我想利用app.config将文件名(密钥)与名称(值)相关联,并在组合框中使名称可用
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Scenario1.doc" value="Hybrid1"/>
<add key="Scenario2.doc" value="Hybrid2"/>
<add key="Scenario3.doc" value="Hybrid3"/>
</appSettings>
</configuration>
这会有效吗?如何检索数据?
答案 0 :(得分:12)
直接来自docs:
// Get the AppSettings section.
// This function uses the AppSettings property
// to read the appSettings configuration
// section.
public static void ReadAppSettings()
{
try
{
// Get the AppSettings section.
NameValueCollection appSettings =
ConfigurationManager.AppSettings;
// Get the AppSettings section elements.
Console.WriteLine();
Console.WriteLine("Using AppSettings property.");
Console.WriteLine("Application settings:");
if (appSettings.Count == 0)
{
Console.WriteLine("[ReadAppSettings: {0}]",
"AppSettings is empty Use GetSection command first.");
}
for (int i = 0; i < appSettings.Count; i++)
{
Console.WriteLine("#{0} Key: {1} Value: {2}",
i, appSettings.GetKey(i), appSettings[i]);
}
}
catch (ConfigurationErrorsException e)
{
Console.WriteLine("[ReadAppSettings: {0}]",
e.ToString());
}
}
因此,如果您想要访问设置Scenario1.doc
,您可以这样做:
var value = ConfigurationManager.AppSettings["Scenario1.doc"];
编辑:
正如Gabriel GM在评论中所说,你必须添加对System.Configuration
的引用。
答案 1 :(得分:0)
app设置用于存储特定于应用程序/环境的设置,而不是存储绑定到UI的数据。
如果由于奇怪的业务请求而无法避免存储在配置中,我宁愿坚持一个单一的设置
<add key="FileDropDown" value="File1-Value|File2-Value" />
并编写C#代码以获取此设置ConfigurationManager.AppSettings["FileDropDown"]
并执行一些字符串拆分(&#39; |&#39;)和(&#39; - &#39;)来创建kvp集合并绑定它到用户界面。