Click here to Skip to main content
13,449,583 members (55,030 online)
Click here to Skip to main content
Add your own
alternative version


92 bookmarked
Posted 15 Oct 2010

Saving Connection Strings to app.config

, 17 Feb 2015
Rate this:
Please Sign up or sign in to vote.
Contrary to several articles, connection strings may be saved to app.config with just a few lines of code.


After finding this simple solution hidden in the patchwork of documentation, I decided to write a brief tour of the basics of the .NET configuration namespaces, as well as share this tip.

The ConfigurationManager namespace, introduced with .NET 2.0, cannot be used to save connections strings. ConfigurationManager.ConnectionStrings.Add() throws an error and System.Configuration.ConfigurationManager does not allow saving to app.config.

While the simplest answer may be to write XML, the .NET 1.1 configuration API System.Configuration.ConnectionStringSettingsCollection supports modification and saving. The last part of this tip is refreshing the 2.0 ConfigurationManager after modifying the config file.

The Basics

The Configuration APIs are confusing, rather than complex. The combination of poorly chosen names and bloated functionality can be navigated safely with a quick guided tour.

Three Configuration Files

There are three filenames: app.config, YOUR_APPLICATION.exe.config, YOUR_APPLICATION.vshost.exe.config.

Copy to Output Directory

App.config is the source file which is copied and renamed when a project is built. The IDE overwrites YOUR_APPLICATION.exe.config with app.config depending on the setting of the “Copy to Output Directory” property. Solution Explorer > app.config > Right-click Properties > Copy to Output Directory. Note that F4 shows the XML document properties if the focus is on the code pane, rather than the solution pane.

Each Section is Different

App.config is divided into sections. Each section has its own handler that defines how to read and write the section. Predefined sections that predate .NET 2.0 have predefined/hardwired handlers. For example, appSettings can be managed using System.Configuration.ConfigurationSection.AppSettingsSection.

Two Similar Sections

There are two sections with similar names: appSettings and applicationSettings. I find it impossible to remember which is which. (The longer name is newer, and is the section added by the IDE starting with .NET 2.0. Solution Explorer > Application Properties > Settings.)

Two Similar Namespaces

There are two similar namespaces: System.Configuration.Configuration and System.Configuration.ConfigurationManager. The longer one (“ConfigurationManager”) is newer. It was introduced in .NET 2.0. While it has nice features like type safety and code generation for each defined setting, it does not support saving applicationSettings or connectionStrings to app.config. The applicationSettings section is read-only.

The applicationSettings section introduced with .NET 2.0 is managed by the System.Configuration.ClientSettingsSection class. Many developers have been stymied and annoyed that the applicationSettings section in app.config is read-only. While the rationale for not storing user preferences in app.config is sound, the inability to persist settings for valid reasons (e.g., installation or configuration) is unnecessarily limiting.

The connectionStrings Section

Some sections, such as the connectionStrings section, can be managed by both namespaces.

For connection strings, the predefined handler is System.Configuration.ConnectionStringSettingsCollection. .NET 2.0 introduced System.Configuration.ConfigurationManager.ConnectionStrings.

Both frameworks can read connection strings from app.config. System.Configuration.ConnectionStringSettingsCollection allows additions.

System.Configuration.ConfigurationManager.ConnectionStrings is a read-only collection that implements Add(), but Add() throws run-time errors.

Using the Code

Saving connection strings is simple when you use the old configuration namespace framework.

/// <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.
      // Save the configuration file.
      // This is needed. Otherwise the connection string does not show up in
      // ConfigurationManager

Points of Interest

  1. The System.Configuration.Configuration namespace supports reading from config files other than app.config. See ConfigurationManager.OpenExeConfiguration and ConfigurationManager.OpenMappedExeConfiguration.
  2. You can move your connection strings to a separate file (much like an include file) by adding a line to your app.config:
    <?xml version="1.0" encoding="utf-8" ?>
          <connectionStrings configSource="connectionstrings.config"/>

    Where connectionstrings.config is the name of the separate file, but could be any name. Note, this file has to be in the same folder (*or deeper) as the config file. This trick can be used to define different NTFS based file-permissions on the connections strings file from the app.config file.

  3. Even when connection strings are in a separate file, System.Configuration.Configuration.Save() writes to the correct file.


  • 10/15/2010: Initial version
  • 1/29/2011: Added complete working example project for C# 2.0 (and above) x86


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


About the Author

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

You may also be interested in...

Comments and Discussions

QuestionI didn't know you could save it like that Pin
Dr Gadgit25-May-15 11:04
memberDr Gadgit25-May-15 11:04 
QuestionProblem Pin
iolah210-Oct-13 0:10
memberiolah210-Oct-13 0:10 
AnswerRe: Problem Pin
aodennison14-Oct-13 11:01
professionalaodennison14-Oct-13 11:01 
GeneralRe: Problem Pin
iolah214-Oct-13 11:20
memberiolah214-Oct-13 11:20 
QuestionNot saving after modified Pin
cardiocom12-Nov-12 7:30
membercardiocom12-Nov-12 7:30 
AnswerRe: Not saving after modified Pin
aodennison12-Nov-12 7:52
memberaodennison12-Nov-12 7:52 
GeneralMy vote of 5 Pin
Mr Pham15-Oct-12 16:44
memberMr Pham15-Oct-12 16:44 
GeneralMy vote of 5 Pin
YPARSARD1-Sep-12 8:24
memberYPARSARD1-Sep-12 8:24 
GeneralMy vote of 5 Pin
Member 10955807-Feb-11 6:03
memberMember 10955807-Feb-11 6:03 
General2nd POI Pin
cjb1102-Feb-11 21:13
membercjb1102-Feb-11 21:13 
GeneralRe: 2nd POI Pin
aodennison5-Feb-11 15:31
memberaodennison5-Feb-11 15:31 
Generalthanks for sharing Pin
Pranay Rana1-Feb-11 23:31
memberPranay Rana1-Feb-11 23:31 
AnswerRe: correction Pin
aodennison29-Jan-11 16:46
memberaodennison29-Jan-11 16:46 
GeneralMy vote of 5 Pin
linuxjr17-Oct-10 10:07
memberlinuxjr17-Oct-10 10:07 
GeneralMy vote of 5 Pin
johannesnestler17-Oct-10 2:49
memberjohannesnestler17-Oct-10 2:49 
GeneralMy vote of 5 Pin
Eric Xue (brokensnow)16-Oct-10 13:16
memberEric Xue (brokensnow)16-Oct-10 13:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180318.3 | Last Updated 17 Feb 2015
Article Copyright 2010 by aodennison
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid