在WinForm中,我们可以使用.NET Framework提供的System.Configuration命名空间中的ConfigurationManager类来保存和读取应用程序的配置信息,以下是详细的步骤:

(图片来源网络,侵删)
1. 创建应用程序配置文件
在WinForm项目中,默认会有一个名为App.config的应用程序配置文件,我们可以在这个文件中添加自定义的配置信息,我们可以添加一个名为MyAppSettings的配置节,用于存储一些自定义的设置:
<configuration>
<configSections>
<section name="MyAppSettings" type="System.Configuration.DictionarySectionHandler, System.Configuration" />
</configSections>
<MyAppSettings>
<add key="Setting1" value="Value1" />
<add key="Setting2" value="Value2" />
</MyAppSettings>
</configuration>
2. 读取配置信息
要读取这些配置信息,我们可以使用ConfigurationManager类的GetSection方法获取相应的配置节,然后将其转换为Dictionary对象,以下是一个示例:
using System;
using System.Configuration;
using System.Collections;
class Program
{
static void Main()
{
// 获取MyAppSettings配置节
object myAppSettings = ConfigurationManager.GetSection("MyAppSettings");
// 将配置节转换为Dictionary对象
var settings = (Hashtable)myAppSettings;
// 读取配置信息
string setting1 = (string)settings["Setting1"];
string setting2 = (string)settings["Setting2"];
Console.WriteLine("Setting1: " + setting1);
Console.WriteLine("Setting2: " + setting2);
}
}
3. 保存配置信息
要保存对配置信息的更改,我们需要使用ConfigurationManager类的OpenExeConfiguration方法打开当前应用程序的可扩展配置,然后使用Save方法保存更改,以下是一个示例:
using System;
using System.Configuration;
class Program
{
static void Main()
{
// 打开当前应用程序的可扩展配置
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 获取MyAppSettings配置节
var myAppSettings = config.GetSection("MyAppSettings") as Hashtable;
// 修改配置信息
if (myAppSettings != null)
{
myAppSettings["Setting1"] = "NewValue1";
myAppSettings["Setting2"] = "NewValue2";
}
// 保存更改
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("MyAppSettings");
}
}
注意:在保存配置信息时,需要调用ConfigurationManager.RefreshSection方法刷新配置节,以便在下次读取时能够获取到最新的配置信息。
本文来自投稿,不代表重蔚自留地立场,如若转载,请注明出处https://www.cwhello.com/450315.html
如有侵犯您的合法权益请发邮件951076433@qq.com联系删除