Hi,
In this article i'll explain howto change Configuration File (App.config or Web.config) programmatically with C# using the ConfigurationManager of System.Configuration.
I based my article on modifying the AppSettings Section of the App.config, but you can also modify any other sections using the same way.
Here is my original App.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SiteName" value="SB2 Developers Blog"/>
</appSettings>
</configuration>
Here is the code in order to get this AppSettings Values (Note that there is a shorter way to display AppSettings values (using ConfigurationManager.AppSettings collection), but this is the way in order to get any other sections from the configuration file.
Here is the code in order to Add new values to the AppSettings Configuration Section.
// Write to Configuration File
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add("Author", "Sb2");
config.Save(ConfigurationSaveMode.Modified);
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SiteName" value="SB2 Developers Blog" />
<add key="Author" value="Sb2" />
</appSettings>
</configuration>
Finally here is the code in order to Change of an existing item of the AppSettings Section.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings["Author"] != null)
{
config.AppSettings.Settings["Author"].Value = "Sb2 Changed";
}
config.Save(ConfigurationSaveMode.Modified);
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SiteName" value="SB2 Developers Blog" />
<add key="Author" value="Sb2 Changed" />
</appSettings>
</configuration>
Hope this help's!
Views(3904)

