Current .Net Version: 2.0.50727
Home
Articles
C# & .Net Framework Reference
Practice C# Online
XML Web Services
RSS Feeds
Code Snippets
T-SQL Scripts
Videos
Valuable Links
Contact Us
Mike's C#, VS.NET and SQL Blog




ROR XML Info.
What's New in .Net 2.0 - Configuring Applications the New Way with the ConfigurationManager Class
Author: Michael G.     Last Updated:12/19/2005 11:44:25 AM
Category(ies): .Net Framework 2.0
Description: Learn how to use the new ConfigurationManager class. The older ConfigurationSettings class is now deprecated.
  Add & View Comments About this Article

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: <?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionstrings> <add name="ConnStr1" connectionstring="Data Source=SERVER1; User ID=sqllogin; Password=password;"/> <add name="ConnStr2" connectionstring="Data Source=SERVER2; User ID=sqllogin; Password=password;"/> </connectionstrings> </configuration> 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: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appsettings> <add key="BackColor" value="White"/> </appsettings> <connectionstrings> <add name="ConnStr1" connectionstring="Data Source=SERVER1; User ID=sqllogin; Password=password;"/> <add name="ConnStr2" connectionstring="Data Source=SERVER2; User ID=sqllogin; Password=password;"/> <add name="ConnStr3" connectionstring="Data Source=SERVER3; User ID=sqllogin; Password=password;"/> </connectionstrings> </configuration>

    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: <?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionstrings> <clear/> </connectionstrings> </configuration>

    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: <?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionstrings> <remove name="ConnStr1"/> </connectionstrings> </configuration> 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: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appsettings> <add key="BackColor" value="White"/> </appsettings> <connectionstrings> <add name="ConnStr1" connectionstring="Data Source=SERVER1; User ID=sqllogin; Password=password;" providername="System.Data.SqlClient"/> <add name="ConnStr2" connectionstring="Data Source=SERVER2; User ID=sqllogin; Password=password;"/> <add name="ConnStr3" connectionstring="Data Source=SERVER3; User ID=sqllogin; Password=password;"/> </connectionstrings> </configuration>

  • 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: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appsettings> <add key="BackColor" value="White"/> </appsettings> <connectionstrings> <add name="ConnStr1" connectionstring="Data Source=SERVER1; User ID=sqllogin; Password=password;"/> <add name="ConnStr2" connectionstring="Data Source=SERVER2; User ID=sqllogin; Password=password;"/> </connectionstrings> </configuration> After: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appsettings> <add key="BackColor" value="White"/> <add key="NewKey" value="New Value"/> </appsettings> <connectionstrings> <add name="ConnStr1" connectionstring="Data Source=SERVER1; User ID=sqllogin; Password=password;"/> <add name="ConnStr2" connectionstring="Data Source=SERVER2; User ID=sqllogin; Password=password;"/> </connectionstrings> </configuration>

    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: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appsettings> <add key="BackColor" value="White"/> <add key="NewKey" value="New Value,New Value"/> </appsettings> <connectionstrings> <add name="ConnStr1" connectionstring="Data Source=SERVER1; User ID=sqllogin; Password=password;"/> <add name="ConnStr2" connectionstring="Data Source=SERVER2; User ID=sqllogin; Password=password;"/> </connectionstrings> </configuration> 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");

    Comments Click Here to Add your Comment
    By Eric Decker @ 1/13/2006 11:02:00 PM

    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.
     
    COPYRIGHT/DISCLAIMER | CONTACT US