Wednesday, May 14, 2008

Reading & Writing other application config files

I recently had to write a configuration tool to manage the configuration settings of a bunch of other programs. 
Here's a little snippet, which also shows using XPath to read XML.




using System.Xml.XPath;


private string ReadOtherAppConfigSetting(string fileName, string setting)
{
string result = "";

try
{
XmlDocument exeConfig = new XmlDocument();
exeConfig.Load(fileName);
XPathNavigator xNav = exeConfig.CreateNavigator();
XPathExpression dsExpr = xNav.Compile("//configuration/appsettings/add[@key='"+setting+"']");
XPathNodeIterator iterator = xNav.Select(dsExpr);

if (iterator.Count == 1)
{
if (iterator.CurrentPosition == 0)
{
iterator.MoveNext();
}

result = iterator.Current.GetAttribute("value", "");
}
}
catch {} //Don't care if can't find or doesn't exist as can default to empty string

return result;
}

private bool WriteOtherAppConfigSetting(string fileName, string setting, string newValue)
{
bool result = false;

XmlDocument exeConfig = new XmlDocument();
XmlNode oldNode = null;

if (File.Exists(fileName))
{
exeConfig.Load(fileName);

try
{
oldNode = exeConfig.DocumentElement.SelectSingleNode("//configuration/appsettings/add[@key='"+setting+"']");
}
catch {} //old child or file may not exist

//Delete existing entry (if exists)
if (oldNode != null)
{
exeConfig.LastChild.FirstChild.RemoveChild(oldNode);
}
}
else
{
//If file doesn't exist, create a basic structure
exeConfig.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><configuration><appsettings></appsettings></configuration>");
}

try
{
//add the new setting
XmlElement newNode = exeConfig.CreateElement("add");
newNode.SetAttribute("key", setting);
newNode.SetAttribute("value", newValue);

exeConfig.LastChild.FirstChild. AppendChild(newNode);
exeConfig.Save(fileName);
result = true;
}
catch
{
throw new IOException("Unable to save configuration settings. Manually edit config file or delete it and then try resaving settings.");
}

return result;
}

0 comments:

Post a Comment

I get a lot of comment spam :( - moderation may take a while.