This will help you out!
/// <summary>
/// Add a connection string to the connection
/// strings section and store it in the
/// configuration file.
/// </summary>
/// <param name="csName">The name of the property.</param>
/// <param name="connectionString">The connectionstring as specified.</param>
public static void AddConnectionStrings(string csName, string connectionString)
{
// Get the configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Add the connection string.
ConnectionStringsSection csSection = config.ConnectionStrings;
csSection.ConnectionStrings.Add(
new ConnectionStringSettings(csName,
connectionString, "System.Data.SqlClient"));
// Save the configuration file.
config.Save(ConfigurationSaveMode.Full);
}
Well for updating it was hard to find any usefull
code to update a connectionstring. It wasn't possible
to update a connectionstring, so I had the remove the
connectionstring, and add a new one. Well isn't that odd??
Microsoft left something undone... Well maybe it isn't usefull
to change your app.config, but well, I had to make it anyhow.
So dynamic app.config or web.config files is little bit strange, because you can't dynamically update it. No you have to remove it first by the configurationmanager.
/// <summary>
/// First remove the old connectionstring and after that
/// add a connection string to the connectionstrings
/// section and store it in the configuration file.
/// </summary>
/// <param name="csName">The name of the property.</param>
/// <param name="connectionString">The connectionstring as specified.</param>
public static void UpdateConnectionStrings(string csName, string connectionString)
{
// Get the configuration file
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Remove the existing connectionstring.
config.ConnectionStrings.ConnectionStrings.Remove(csName);
// Add the connectionstring
ConnectionStringsSection csSection = config.ConnectionStrings;
csSection.ConnectionStrings.Add(
new ConnectionStringSettings(csName,
connectionString, "System.Data.SqlClient"));
// Save the configuration file
config.Save(ConfigurationSaveMode.Full);
}