Tested with Microsoft Visual Studio 2005 8.0.50727.42; .NET Framework 2.0.50727
A New Way of Dealing with Configuration Settings
Microsoft now disapproves of the use of ConfigurationSettings (in the System.Configuration namespace) for the
retrieval of application and machine configuration settings (from the application.exe.config and machine.config files
respectively). The .Net Framework 2.0 now exposes a ConfigurationManager class that "replaces" ConfigurationSettings.
A new FCL assembly has been added that incorporates the new ConfigurationManager class: System.Configuration.dll.
If you plan on leveraging the functionality of ConfigurationManager, ensure you add a reference to this assembly.
Note: the following examples make use of the
and
statements.
The Old Way of Retrieving an Application Configuration Setting:
Color colorBack = Color.FromName(ConfigurationSettings.AppSettings["BackColor"]);
The New Way of Retrieving an Application Configuration Setting:
Color colorBack = Color.FromName(ConfigurationManager.AppSettings["BackColor"]);
ConfigurationManager is a static class that exposes methods and properties that allow you to manipulate both an
application (app.config) and machine (machine.config) configuration file.
ConfigurationManager Members that Deal with the Current Running Application:
AppSettings: This property returns a NameValueConnection object that holds all of the
settings in the configuration file's appSettings section.
ConnectionStrings: This property returns a ConnectionStringSettingsCollection object
that holds all of the connection string settings in the configuration file's connectionStrings section.
GetSection: This method returns a custom configuration section.
RefreshSection: This method refreshes a section of the configuration file in such a way
that the application will re-read the settings from the configuration file.
ConfigurationManager Members that Deal with a Separate Application or the Current Machine:
OpenExeConfiguration: This method returns a Configuration object that holds all of
the settings for a separate application configuration file.
OpenMachineConfiguration: This method returns a Configuration object that holds all of
the settings for the current machine configuration file.
OpenMappedExeConfiguration: This method returns a Configuration object that holds all of
the settings for a mapped application configuration file.
OpenMappedMachineConfiguration: This method returns a Configuration object that holds all of
the settings for a mapped current machine configuration file.
connectionStrings Configuration Section Added
A Sample Appication Configuration File with a connectionStrings Configuration Section Added:Retrieving a connection string:
// Load the current application's configuration file:
Configuration config =
ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
// Using the name of the connection string (defined in the configuration file by
// the connectionString atttribute; in this case, connectionString="ConnStr1"):
ConnectionStringSettings connstr =
config.ConnectionStrings.ConnectionStrings["ConnStr1"];
String strConn = connstr.ConnectionString;
// Using the oridinal/index position connection string
// (defined in the configuration file by the position of the "add" node):
ConnectionStringSettings connstr =
config.ConnectionStrings.ConnectionStrings[0];
String strConn = connstr.ConnectionString;
Adding a New Connection String:
// Load the current application's configuration file:
Configuration config =
ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
// Create a ConnectionStringSettings Object:
ConnectionStringSettings connStrSettings = new ConnectionStringSettings("ConnStr3",
"Data Source=SERVER3; User ID=sqllogin; Password=password;");
// Add the object to the ConnectionStringSettingsCollection collection:
config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);
// Save the changes back to disk;
config.Save();
After Adding a Configuration String Key-Value Pair Node to the Application Configuration File:
Removing All Connection Strings:
- Via Code:
// For the current application:
ConfigurationManager.ConnectionStrings.Clear();
// For another application:
Configuration config =
ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
// Note that Application.ExecutablePath is the path to the executable,
// not the application's configuration file; do not use the path to the
// configuration file.
config.ConnectionStrings.ConnectionStrings.Clear();
- Via the Configuration File:
Removing a Specific Connection String:
- Via Code:
// For the current application (where ConnStr1 is the "name" in the
// configuration file):
ConfigurationManager.ConnectionStrings.Remove("ConnStr1");
// For another application (where ConnStr1 is the "name" in the
// configuration file):
Configuration config =
ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
// Note that Application.ExecutablePath is the path to the executable,
// not the application's configuration file; do not use the path to the
// configuration file.
config.ConnectionStrings.ConnectionStrings.Remove("ConnStr1");
- Via the Configuration File:Specifying a Connection String Provider Name
Each connection string in the configuration file can also have an accompanying data provider name.
It must be one of the namespaced ADO.NET data providers in the FCL (Framework Class Library), such as
System.Data.SqlClient, System.Data.OleDb, System.Data.Odbc and System.Data.OracleClient.
Setting the providerName Attribute of an Existing Key-Pair Value Node in the Application Configuration File
and Saving to Disk:
// Load the current application's configuration file:
Configuration config =
ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
// Get the connection string whos name is "ConnStr1":
ConnectionStringSettings connStrSettings =
config.ConnectionStrings.ConnectionStrings["ConnStr1"];
// Set the ProviderName (providerName in the config. file):
connStrSettings.ProviderName = "System.Data.SqlClient";
// Save changes back to disk:
config.Save();
After:
Saving Configuration Information to Disk
You can now save the changes made to connection settings in memory to disk. To do this, you need to specifically
create a Configuration object based on an existing configuration file.
In the following example, I'm creating a Configuration object based on the configuration file of the current
application, adding a new AppSettings node and then saving it back to disk.
Adding a New Key-Value Pair Node to the Current Application Configuration File and Saving to Disk:
// Load the current application's configuration file:
Configuration config =
ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
// Create a new AppSettings key-value pair entry:
config.AppSettings.Settings.Add("NewKey", "New Value");
// Save the changes back to the original configuration file:
config.Save();
Before:After:
Beware of Using Add() to Add Key-Value Pairs to Existing Nodes
In the preceding example, I added a single key-value pair node with the name "NewKey" to the application's
configuration file. If I continue to call that same method while using the same key name "NewKey", the CLR
will append the value "New Value" to the "value" attribute of that node:
The Results of Calling Configuration.AppSettings.Settings.Add Twice and Saving to Disk:Removing an Existing Key-Value Pair Node from the Current Application Configuration File and Saving to Disk:
// Load the current application's configuration file:
Configuration config =
ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
// Remove an existing AppSettings key-value pair entry:
config.AppSettings.Settings.Remove("NewKey");
// Save the changes back to the original configuration file:
config.Save();
Making a Copy of the Current Application Configuration File:
// Load the current application's configuration file:
Configuration config =
ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
// Save it as another file:
config.SaveAs(Application.ExecutablePath + ".config.bak");
What do you know about encrypting connection strings in the config file?By Michael G. @ 1/14/2006 8:06:12 PM
Read my article entitled "What's New in .Net 2.0 - Protect Database Strings with ProtectedData" for an answer.By adam @ 4/2/2006 10:52:35 AM
how about how to change a setting?By enewmen @ 6/21/2006 12:15:37 PM
How does one create a new config file at runtime? - Without creating a file using new XmlTextWriter(filename, null);
I hope there is something more elegant.
By natea @ 8/23/2006 5:31:32 PM
How do you get this to work if you want a .dll to read it's config file. I have run into some issues in getting the config file to copy over for unit test.By Someone @ 11/28/2006 1:02:57 AM
Bit late, but answer to the last question is to use a postbuild event to perform a copy of the config from its source directory into the bin/debug directory (something like copy ../../*.config)
By Mexican Food Fan @ 5/16/2007 4:03:34 PM
Could you please illustrate about how to handle Custom Configuration Sections? Thanks.By buy viagra @ 7/25/2007 3:41:24 PM