Click here to Skip to main content
15,895,084 members
Articles / Programming Languages / XML

Saving Connection Strings to app.config

Rate me:
Please Sign up or sign in to vote.
4.82/5 (27 votes)
17 Feb 2015CPOL3 min read 135.6K   4K   94  
Contrary to several articles, connection strings may be saved to app.config with just a few lines of code.
/// <summary>
/// Adds a connection string settings entry & saves it to the associated config file.
///
/// This may be app.config, or an auxiliary file that app.config points to or some
/// other xml file.
/// ConnectionStringSettings is the confusing type name of one entry including: 
/// name + connection string + provider entry
/// </summary>
/// <param name="configuration">Pass in ConfigurationManager.OpenMachineConfiguration, 
/// ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) etc. </param>
/// <param name="connectionStringSettings">The entry to add</param>

public static void AddAndSaveOneConnectionStringSettings(
       System.Configuration.Configuration configuration,
       System.Configuration.ConnectionStringSettings connectionStringSettings)
{
      // You cannot add to ConfigurationManager.ConnectionStrings using
      // ConfigurationManager.ConnectionStrings.Add(connectionStringSettings) -- This fails.
 
      // But you can add to the configuration section and refresh the ConfigurationManager.
 
      // Get the connection strings section; Even if it is in another file.
      ConnectionStringsSection connectionStringsSection = configuration.ConnectionStrings;
 
      // Add the new element to the section.
      connectionStringsSection.ConnectionStrings.Add(connectionStringSettings);
 
      // Save the configuration file.
      configuration.Save(ConfigurationSaveMode.Minimal);
 
      // This is this needed. Otherwise the connection string does not show up in
      // ConfigurationManager
      ConfigurationManager.RefreshSection("connectionStrings");
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Software Developer
United States United States
I been programming since before a man walked on the moon, and still love it.

Comments and Discussions