Wednesday, November 23, 2011

Modifying Configuration Settings at Runtime

Adding New Key-Value Pairs
// 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;
}
}

Updating Key-Value Pairs
// 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);
}

Deleting Key-Value Pairs
// 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);
}

Helper Method
// 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;
}

No comments:

Post a Comment