gpt4 book ai didi

c# - 如何从 WinForms 中的 app.config 读取 AppSettings

转载 作者:太空狗 更新时间:2023-10-29 18:22:44 24 4
gpt4 key购买 nike

我通常使用文本文件作为配置。但是这次我想利用 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>

这行得通吗?如何检索数据?

最佳答案

直接来自 docs :

using System.Configuration;

// 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 的引用。

关于c# - 如何从 WinForms 中的 app.config 读取 AppSettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12731683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com