Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Programatically update connectionstring using C#

4.17/5 (6 votes)
8 Nov 2011CPOL 19.8K  
You can do the same using the configuration-specific parts of the .NET Framework to save some of the hard work:// Get the configuration file.System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);//Initialize the Connection...

You can do the same using the configuration-specific parts of the .NET Framework to save some of the hard work:


C#
// Get the configuration file.
System.Configuration.Configuration config = 
  ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

//Initialize the Connection string builder
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
{
   InitialCatalog = "YOUR_DATABASE",
   IntegratedSecurity = true,
   Password = "YOUR_PASSWORD"
};

// Add the connection string.
config.ConnectionStrings.ConnectionStrings["CONNECTION_NAME"].ConnectionString = 
       sqlBuilder.ConnectionString;

// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);

It'll achieve the same result provided you have the right permissions, only you don't have to treat the config file as a generic XmlDocument and parse the items to find the correct section.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)