在WinForm程序中读写系统配置

1.在MSDN上提供了VS2005对Settings.setting文件的读写操作
======================================================
在 C# 中使用设置
http://www.microsoft.com/china/msdn/library/langtool/vcsharp/SettingsCSRL.mspx?mfr=true

在运行时读取设置:
------------------
this.BackColor = Properties.Settings.Default.myColor;

在运行时写入和保持用户设置的步骤:
----------------------------------
访问用户设置并为其分配新值,如下例所示:
Properties.Settings.Default.myColor = Color.AliceBlue;
如果要保持在应用程序会话之间对用户设置所做的更改,
请调用 Save 方法,如以下代码所示:
Properties.Settings.Default.Save();

交替使用多组设置
================
在某些情况下,可能需要在应用程序中使用多组设置。
例如,如果正在开发的应用程序中有某组设置预计会频繁进行更改,
则比较明智的做法是将其全都分成单个文件,这样便可成批替换相应文件,
而不会使其他设置受到影响。
Visual Studio 2005 允许向项目中添加多组设置。
可以通过各自节点中生成的设置对象来访问各组附加设置。
例如,如果向项目中添加了名为 SpecialSettings 的一组设置,
则要通过 Properties.SpecialSettings 对象来访问该组设置包含在代码中的设置。

添加附加设置组的步骤

1).从“Project”(项目)菜单中选择“Add New Item”(添加新项)。
将会打开“Add New Item”(添加新项)对话框。
 
2).在“Add New Item”(添加新项)对话框中,选择“Settings File”(设置文件)。
 
3).在“Name”(名称)框中为设置文件命名,如 SpecialSettings.settings,
然后单击“Add”(添加),将文件添加到解决方案中。
 
4).在“Solution Explorer”(解决方案资源管理器)中,
将新的设置文件拖入到 Properties 文件夹中。
这样便可在代码中使用新的设置。
 
5).如在其他任何设置文件中那样在此文件中添加和使用设置。
可通过 Properties.SpecialSettings 对象访问此组设置。
 

2.有网友提供如下操作类
=======================
用这个类:
using System;
using System.Xml;
using System.Windows.Forms;

namespace Common
{
/// <summary>
/// 模块名称: 读写系统配置类
/// 编写日期: 2005-12-01
/// </summary>
public class AppConfig
{
public static bool UpdateConfig(string strKey, string strValue)
{
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Application.ExecutablePath + ".config");
XmlNode node = doc.SelectSingleNode(@"//add[@key='" + strKey + "']");
XmlElement ele = (XmlElement)node;
ele.SetAttribute("value", strValue);
doc.Save(Application.ExecutablePath + ".config");
}
catch
{
return false;
}
return true;
}
public AppConfig()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static string GetConfig(string strKey)
{
//return System.Configuration.ConfigurationManager.AppSettings[strKey];
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Application.ExecutablePath + ".config");
XmlNode node = doc.SelectSingleNode(@"//add[@key='" + strKey + "']");
XmlElement ele = (XmlElement)node;
return ele.GetAttribute("value");
}
catch
{
return string.Empty;
}
}
}
}

posted on 2007-09-18 09:30  freeliver54  阅读(892)  评论(0编辑  收藏  举报

导航