Wednesday, January 7, 2009

Updating App.config

Today I faced the problem to update the App.config. There exist several solutions out there but I was not able to find a simple one. Therefore I decided to try out the new Linq to XML feature of .NET 3.5 and wrote the following method which updates the value of a specific key in the App.config file:

public static void UpdateAppConfig(string key, object value)
{
if (key == null)
throw new ArgumentNullException("key");

if (value == null)
throw new ArgumentNullException("value");

XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var result = (from appSetting in doc.Descendants("appSettings").Descendants("add")
where appSetting.Attribute("key").Value.Equals(key)
select appSetting).FirstOrDefault();

if (result != null)
{
result.Attribute("value").SetValue(value);
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
doc = null;
}
else
{
Console.WriteLine("The application setting with key '{0}' was not found!", key);
}
}

1 comment:

Unknown said...

Interesting. Linq to XML is really cool, and most important, it's simple!
I played a bit around with it when I experimented with Silverlight but didn't do any further (deeper) tryouts yet.