Export (0) Print
Expand All

ConfigurationManager Class

Provides access to configuration files for client applications. This class cannot be inherited.

Namespace: System.Configuration
Assembly: System.Configuration (in system.configuration.dll)

public static class ConfigurationManager
public final class ConfigurationManager
public final class ConfigurationManager
Not applicable.

The ConfigurationManager class enables you to access machine, application, and user configuration information. This class replaces the ConfigurationSettings class, which is deprecated.

You can use the built-in System.Configuration types or derive from them to handle configuration information. By using these types, you can work directly with configuration information and you can extend configuration files to include custom information.

The ConfigurationManager class includes members that enable you to perform the following tasks:

  • Read a section from a configuration file. To access configuration information, call the GetSection method. For some sections such as appSettings and connectionStrings, use the AppSettings and ConnectionStrings classes. These members perform read-only operations, use a single cached instance of the configuration, and are multithread aware.

  • Read and write configuration files as a whole. Your application can read and write configuration settings at any level, for itself or for other applications or computers, locally or remotely. Use one of the methods provided by the ConfigurationManager class to open a configuration file such as SampleApp.exe.config. These methods return a Configuration object that in turn exposes methods and properties you can use to work with the associated configuration files. The methods perform read or write operations and create the configuration data every time that a file is written.

  • Support configuration tasks. The following types are used to support various configuration tasks:

    In addition to working with existing configuration information, you can create and work with custom configuration elements by extending the built-in configuration types such as the ConfigurationElement, ConfigurationElementCollection, ConfigurationProperty, and ConfigurationSection classes. For an example of how to extend a built-in configuration type programmatically, see ConfigurationSection. For an example of how to extend a built-in configuration type that uses the attribute-based model, see ConfigurationElement.

Notes to Implementers: The Configuration class enables programmatic access for editing configuration files. You use one of the Open methods provided by ConfigurationManager. These methods return a Configuration object, which in turn provides the required methods and properties to handle the underlying configuration files. You can access these files for reading or writing. To read the configuration files, use GetSection or GetSectionGroup to read configuration information. The user or process that reads must have the following permissions:

  • Read permission on the configuration file at the current configuration hierarchy level.

  • Read permissions on all the parent configuration files.

If your application needs read-only access to its own configuration, we recommend that you use the GetSection method. This method provides access to the cached configuration values for the current application, which has better performance than the Configuration class. To write to the configuration files, use one of the Save methods. The user or process that writes must have the following permissions:
  • Write permission on the configuration file and directory at the current configuration hierarchy level.

  • Read permissions on all the configuration files.

The following code example shows how to use the ConfigurationManager class to access the appSettings configuration section. If the section does not exist, it is created and added to the configuration file.

using System;
using System.Collections.Specialized;
using System.Collections.ObjectModel;
using System.Collections;
using System.Text;
using System.Configuration;

namespace Samples.AspNet
{
    class UsingConfigurationManager
    {

        // Show how to use AppSettings.
        static void DisplayAppSettings()
        {

            // Get the AppSettings collection.
            NameValueCollection appSettings =
               ConfigurationManager.AppSettings;

            string[] keys = appSettings.AllKeys;

            Console.WriteLine();
            Console.WriteLine("Application appSettings:");

            // Loop to get key/value pairs.
            for (int i = 0; i < appSettings.Count; i++)

                Console.WriteLine("#{0} Name: {1} Value: {2}",
                  i, keys[i], appSettings[i]);

        }

        // Show how to use ConnectionStrings.
        static void DisplayConnectionStrings()
        {

            // Get the ConnectionStrings collection.
            ConnectionStringSettingsCollection connections =
                ConfigurationManager.ConnectionStrings;

            Console.WriteLine();
            Console.WriteLine("Connection strings:");


            // Loop to get the collection elements.
            IEnumerator conEnum =
                connections.GetEnumerator();

            int i = 0;
            while (conEnum.MoveNext())
            {
                string name = connections[i].Name;
                string connectionString = connections[name].ConnectionString;
                string provider = connections[name].ProviderName;

                Console.WriteLine("Name:               {0}", name);
                Console.WriteLine("Connection string:  {0}", connectionString);
                Console.WriteLine("Provider:           {0}", provider);
            }

        }

        // Show how to use OpenMachineConfiguration.
        static void DisplayMachineConfigSections()
        {
            // Get the machine.config file.
            Configuration machineConfig =
                ConfigurationManager.OpenMachineConfiguration();
            
            ConfigurationSectionCollection sections = machineConfig.Sections;

            Console.WriteLine(); 
            Console.WriteLine("Sections in machine.config:");

            // Loop to get the sections machine.config.
            foreach (ConfigurationSection section in sections)
            {
                string name = section.SectionInformation.Name;
                Console.WriteLine("Name: {0}", name);
            }
   
        }


        // Show how to use OpenExeConfiguration(ConfigurationUserLevel) 
        // and RefreshSection.
        static void UpdateAppSettings()
        {
            // Get the configuration file.
            System.Configuration.Configuration config =
              ConfigurationManager.OpenExeConfiguration(
              ConfigurationUserLevel.None);

            // Add an entry to appSettings.
            int appStgCnt = 
                ConfigurationManager.AppSettings.Count;
            string newKey = "NewKey" + appStgCnt.ToString();

            string newValue = DateTime.Now.ToLongDateString() + " " +
                           DateTime.Now.ToLongTimeString();

            config.AppSettings.Settings.Add(newKey, newValue);

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

            // Force a reload of the changed section.
            ConfigurationManager.RefreshSection("appSettings");

        }

        // Show how to use OpenExeConfiguration(string).
        static void DisplayAppSettingsRawXml()
        {

            
            // Get the application path.
            string exePath = System.IO.Path.Combine(
                Environment.CurrentDirectory, "ConfigurationManager.exe");

            // Get the configuration file.
            System.Configuration.Configuration config =
              ConfigurationManager.OpenExeConfiguration(exePath);

            // Get the AppSetins section.
            AppSettingsSection appSettingSection = config.AppSettings;

            // Display raw xml.
            Console.WriteLine(appSettingSection.SectionInformation.GetRawXml());

         
        }

        // Show how to use GetSection.
        static void DisplayAppSettingsSectionRawXml()
        {

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

            // Get the AppSetins section.
            AppSettingsSection appSettingSection = 
                (AppSettingsSection)config.GetSection("appSettings");

            // Display raw xml.
            Console.WriteLine(appSettingSection.SectionInformation.GetRawXml());


        }

        // Show how to use OpenMappedMachineConfiguration.
        static void DisplayMappedMachineConfigurationFileSections()
        {
            // Get the machine.config file.
            Configuration machineConfig =
                ConfigurationManager.OpenMachineConfiguration();

            // Map to the machine configuration file.
            ConfigurationFileMap configFile = 
                new ConfigurationFileMap(machineConfig.FilePath);
            Configuration config =
                ConfigurationManager.OpenMappedMachineConfiguration(configFile);

            // Display the configuration file sections.
            ConfigurationSectionCollection sections = config.Sections;

            Console.WriteLine();
            Console.WriteLine("Sections in machine.config:");

            // Loop to get the sections machine.config.
            foreach (ConfigurationSection section in sections)
            {
                string name = section.SectionInformation.Name;
                Console.WriteLine("Name: {0}", name);
            }

        }


        // Show how to use OpenMappedExeConfiguration.
        static void DisplayMappedExeConfigurationFileSections()
        {
            // Get the application configuration file path.
            string exeFilePath = System.IO.Path.Combine(
                Environment.CurrentDirectory, "ConfigurationManager.exe.config");

            // Map to the application configuration file.
            ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
            configFile.ExeConfigFilename = exeFilePath;
            Configuration config =
                ConfigurationManager.OpenMappedExeConfiguration(configFile, 
                ConfigurationUserLevel.None);

            // Display the configuration file sections.
            ConfigurationSectionCollection sections = config.Sections;

            Console.WriteLine();
            Console.WriteLine("Sections in machine.config:");

            // Loop to get the sections machine.config.
            foreach (ConfigurationSection section in sections)
            {
                string name = section.SectionInformation.Name;
                Console.WriteLine("Name: {0}", name);
            }

        }

        static void Main(string[] args)
        {

            // Show how to use OpenExeConfiguration() and RefreshSection.
            UpdateAppSettings();

            // Show how to use AppSettings.
            DisplayAppSettings();

            // Show how to use ConnectionStrings.
            DisplayConnectionStrings();

            // Show how to use OpenExeConfiguration(string).
            DisplayAppSettingsRawXml();

            // Show how to use GetSection.
            DisplayAppSettingsSectionRawXml();

            // Show how to use OpenMappedMachineConfiguration.
            DisplayMappedMachineConfigurationFileSections();

            // Show how to use OpenMappedExeConfiguration.
            DisplayMappedExeConfigurationFileSections();

            // Show how to use OpenMachineConfiguration.
            DisplayMachineConfigSections();

        }
    }

}

The example works with the elements illustrated in the following configuration file, which is generated the first time that you run the example.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="NewKey0" value="Monday, January 23, 2006 2:56:14 PM" />
    <add key="NewKey1" value="Monday, January 23, 2006 3:15:18 PM" />
    <add key="NewKey2" value="Monday, January 23, 2006 3:16:29 PM" />
  </appSettings>
</configuration>

System.Object
  System.Configuration.ConfigurationManager

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

Community Additions

ADD
Show:
© 2014 Microsoft