在运行时修改配置设置






4.67/5 (15投票s)
2006年1月3日
2分钟阅读

189371
本文将演示如何在 App.config 文件中添加、删除和更新键值对。
引言
本文将演示如何在运行时在App.config文件中添加、删除和更新键值对。
背景
Visual Studio .NET 已经暗示,更强大的运行时修改App.config文件的支持将在 .NET 2.0 发布时到来。 由于我不想等那么久,我提供了以下包含四个方法的类,使您能够在运行时修改App.config(或Web.config,只需进行一些小的更改)。 你们中的一些人可能已经注意到访问System.Configuration.ConfigurationSettings.AppSettings.Add("key","value")
会抛出异常(集合是只读的)。 为了解决这个问题,我编写了以下方法,希望如果您有一个应用程序需要用户在运行时添加、编辑或删除数据库连接字符串或其他此类配置数据,这将非常有用。
使用代码
在我们开始之前,我想先对本文做一个免责声明。 如果管理不当,在运行时修改配置文件可能会导致应用程序内部出现一些令人讨厌的、意想不到的行为。 我只是给出代码,它将向您展示如何做到这一点--在确定要编辑哪些键值对时,请遵守您自己的良好判断!
添加新的键值对
以下方法演示如何向配置添加键和值。 它将App.config作为 XML 文档加载,将键名和值添加到appSettings
节点,并将文档保存在两个位置。 它将使用辅助方法KeyExists
来确保配置中尚不存在该键。
// Adds a key and value to the App.config
public void AddKey(string strKey, string strValue)
{
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
try
{
if (KeyExists(strKey))
throw new ArgumentException("Key name: <" + strKey +
"> already exists in the configuration.");
XmlNode newChild = appSettingsNode.FirstChild.Clone();
newChild.Attributes["key"].Value = strKey;
newChild.Attributes["value"].Value = strValue;
appSettingsNode.AppendChild(newChild);
//We have to save the configuration in two places,
//because while we have a root App.config,
//we also have an ApplicationName.exe.config.
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory +
"..\\..\\App.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
catch (Exception ex)
{
throw ex;
}
}
更新键值对
以下方法更新App.config中现有的键值对。 它将利用辅助方法KeyExists
来确保我们有一个键要更新。
// Updates a key within the App.config
public void UpdateKey(string strKey, string newValue)
{
if (!KeyExists(strKey))
throw new ArgumentNullException("Key", "<" + strKey +
"> does not exist in the configuration. Update failed.");
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
// Attempt to locate the requested setting.
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
childNode.Attributes["value"].Value = newValue;
}
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory +
"..\\..\\App.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
删除键值对
以下方法将从App.config中删除现有的键值对。 它将利用辅助方法KeyExists
来确保我们有一个键要删除。
// Deletes a key from the App.config
public void DeleteKey(string strKey)
{
if (!KeyExists(strKey))
throw new ArgumentNullException("Key", "<" + strKey +
"> does not exist in the configuration. Update failed.");
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
// Attempt to locate the requested setting.
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
appSettingsNode.RemoveChild(childNode);
}
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
辅助方法
KeyExists
是一个简单的辅助方法,它返回一个布尔值,指示目标键是否实际存在于App.config中。 它在上述所有三种方法中使用。
// Determines if a key exists within the App.config
public bool KeyExists(string strKey)
{
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
// Attempt to locate the requested setting.
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
return true;
}
return false;
}
关注点
这就是事情的来龙去脉。 我不会包含项目,因为这些方法相当简单。 常识会告诉我们,我们的应用程序将需要对App.config的读/写权限才能保存更改。 同样值得注意的是配置文件的行为。 一旦我们的 Forms 应用程序加载完毕,App.config就已经加载完毕,所以,如果你正在做一些事情,比如从配置中加载数据库,你可能不想使用常见的System.Configuration.ConfigurationSettings.AppSettings["key"]
语法。 最好像这样遍历App.config作为 XML 文档
//This code will add a listviewitem
//to a listview for each database entry
//in the appSettings section of an App.config file.
private void loadFromConfig()
{
this.lstDatabases.Items.Clear();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory +
"..\\..\\App.config");
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
foreach (XmlNode node in appSettingsNode.ChildNodes)
{
ListViewItem lvi = new ListViewItem();
string connStr = node.Attributes["value"].Value.ToString();
string keyName = node.Attributes["key"].Value.ToString();
lvi.Text = keyName;
lvi.SubItems.Add(connStr);
this.lvDatabases.Items.Add(lvi);
}
}
祝您编码愉快!