Export (0) Print
Expand All

ConfigurationManager Class

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

System.Object
  System.Configuration.ConfigurationManager

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

public static class ConfigurationManager

The ConfigurationManager type exposes the following members.

  NameDescription
Public propertyStatic memberAppSettingsGets the AppSettingsSection data for the current application's default configuration.
Public propertyStatic memberConnectionStringsGets the ConnectionStringsSection data for the current application's default configuration.
Top

  NameDescription
Public methodStatic memberGetSectionRetrieves a specified configuration section for the current application's default configuration.
Public methodStatic memberOpenExeConfiguration(ConfigurationUserLevel)Opens the configuration file for the current application as a Configuration object.
Public methodStatic memberOpenExeConfiguration(String)Opens the specified client configuration file as a Configuration object.
Public methodStatic memberOpenMachineConfigurationOpens the machine configuration file on the current computer as a Configuration object.
Public methodStatic memberOpenMappedExeConfiguration(ExeConfigurationFileMap, ConfigurationUserLevel)Opens the specified client configuration file as a Configuration object that uses the specified file mapping and user level.
Public methodStatic memberOpenMappedExeConfiguration(ExeConfigurationFileMap, ConfigurationUserLevel, Boolean)Opens the specified client configuration file as a Configuration object that uses the specified file mapping, user level, and preload option.
Public methodStatic memberOpenMappedMachineConfigurationOpens the machine configuration file as a Configuration object that uses the specified file mapping.
Public methodStatic memberRefreshSectionRefreshes the named section so the next time that it is retrieved it will be re-read from disk.
Top

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

To use the ConfigurationManager class, your project must reference the System.Configuration assembly. By default, some project templates, like Console Application, do not reference this assembly so you must manually reference it.

NoteNote

The name and location of the application configuration file depend on the application's host. For more information, see Application Configuration Files.

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:

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 first example shows a simple console application that reads application settings, adds a new setting, and updates an existing setting.

using System;
using System.Configuration;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ReadAllSettings();
            ReadSetting("Setting1");
            ReadSetting("NotValid");
            AddUpdateAppSettings("NewSetting", "May 7, 2014");
            AddUpdateAppSettings("Setting1", "May 8, 2014");
            ReadAllSettings();
        }

        static void ReadAllSettings()
        {
            try
            {
                var appSettings = ConfigurationManager.AppSettings;

                if (appSettings.Count == 0)
                {
                    Console.WriteLine("AppSettings is empty.");
                }
                else
                {
                    foreach (var key in appSettings.AllKeys)
                    {
                        Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);
                    }
                }
            }
            catch (ConfigurationErrorsException)
            {
                Console.WriteLine("Error reading app settings");
            }
        }

        static void ReadSetting(string key)
        {
            try
            {
                var appSettings = ConfigurationManager.AppSettings;
                string result = appSettings[key] ?? "Not Found";
                Console.WriteLine(result);
            }
            catch (ConfigurationErrorsException)
            {
                Console.WriteLine("Error reading app settings");
            }
        }

        static void AddUpdateAppSettings(string key, string value)
        {
            try
            {
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = configFile.AppSettings.Settings;
                if (settings[key] == null)
                {
                    settings.Add(key, value);
                }
                else
                {
                    settings[key].Value = value;
                }
                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
            }
            catch (ConfigurationErrorsException)
            {
                Console.WriteLine("Error writing app settings");
            }
        }
    }
}

The previous example assumes your project has an App.config file as shown below.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="Setting1" value="May 5, 2014"/>
    <add key="Setting2" value="May 6, 2014"/>
  </appSettings>
</configuration>

The following example shows how to use a connection string to read data from a database.

using System;
using System.Configuration;
using System.Data.SqlClient;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ReadProducts();
        }

        static void ReadProducts()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString;
            string queryString = "SELECT Id, ProductName FROM dbo.Products;";
            using (var connection = new SqlConnection(connectionString))
            {
                var command = new SqlCommand(queryString, connection);
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
                    }
                }
            }
        }
    }
}

The previous example assumes your project has an App.config as shown below.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <connectionStrings>
      <add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False" />
    </connectionStrings>
</configuration>

A Visual Studio Web site project with source code is available to accompany this topic: Download.

The following example shows how to use the ConfigurationManager class in a console application. The code shows the following:

  • How to access the appSettings configuration section. If the section does not exist, it is created and added to the configuration file. The example creates the application configuration file if one does not exist.

  • How to access the Machine.config file to obtain information such as the default connection string, if it is defined, and the sections that are currently configured.

    NoteNote

    When you create a project, make sure to add a reference to the System.Configuration assembly. This assembly contains the ConfigurationManager class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

// The following example shows how to use the ConfigurationManager  
// class in a console application. 
// 
// IMPORTANT: To compile this example, you must add to the project  
// a reference to the System.Configuration assembly. 
//
  #region
  //*** Auxiliary Classes ***//

  // Define a custom configuration element to be  
  // contained by the ConsoleSection. This element  
  // stores background and foreground colors that 
  // the application applies to the console window. 
  public class ConsoleConfigElement : ConfigurationElement
  {
    // Create the element. 
    public ConsoleConfigElement()
    { }

    // Create the element. 
    public ConsoleConfigElement(ConsoleColor fColor, 
        ConsoleColor bColor)
    {
      ForegroundColor = fColor;
      BackgroundColor = bColor;
    }

    // Get or set the console background color.
    [ConfigurationProperty("background",
      DefaultValue = ConsoleColor.Black,
      IsRequired = false)]
    public ConsoleColor BackgroundColor
    {
      get
      {
        return (ConsoleColor)this["background"];
      }
      set
      {
        this["background"] = value;
      }
    }

    // Get or set the console foreground color.
    [ConfigurationProperty("foreground",
       DefaultValue = ConsoleColor.White,
       IsRequired = false)]
    public ConsoleColor ForegroundColor
    {
      get
      {
        return (ConsoleColor)this["foreground"];
      }
      set
      {
        this["foreground"] = value;
      }
    }
  }

  // Define a custom section that is used by the application 
  // to create custom configuration sections at the specified  
  // level in the configuration hierarchy that is in the  
  // proper configuration file. 
  // This enables the user that has the proper access  
  // rights, to make changes to the configuration files. 
  public class ConsoleSection : ConfigurationSection
  {
    // Create a configuration section. 
    public ConsoleSection()
    { }

    // Set or get the ConsoleElement. 
    [ConfigurationProperty("consoleElement")]
    public ConsoleConfigElement ConsoleElement
    {
      get
      {
        return (
          (ConsoleConfigElement) this["consoleElement"]);
      }
      set
      {
        this["consoleElement"] = value;
      }
    }
  }
  #endregion

  #region
  //*** ConfigurationManager Interaction Class ***//

  // The following code uses the ConfigurationManager class to  
  // perform the following tasks: 
  // 1) Get the application roaming configuration file. 
  // 2) Get the application configuration file. 
  // 3) Access a specified configuration file through mapping. 
  // 4) Access the machine configuration file through mapping.  
  // 5) Read a specified configuration section. 
  // 6) Read the connectionStrings section. 
  // 7) Read or write the appSettings section. 
  public static class UsingConfigurationManager
  {

    // Get the roaming configuration file associated  
    // with the application. 
    // This function uses the OpenExeConfiguration( 
    // ConfigurationUserLevel userLevel) method to  
    // get the configuration file. 
    // It also creates a custom ConsoleSection and  
    // sets its ConsoleEment BackgroundColor and 
    // ForegroundColor properties to blue and yellow 
    // respectively. Then it uses these properties to 
    // set the console colors.   
    public static void GetRoamingConfiguration()
    {
      // Define the custom section to add to the 
      // configuration file. 
      string sectionName = "consoleSection";
      ConsoleSection currentSection = null;

      // Get the roaming configuration  
      // that applies to the current user.
      Configuration roamingConfig =
        ConfigurationManager.OpenExeConfiguration(
         ConfigurationUserLevel.PerUserRoaming);

      // Map the roaming configuration file. This 
      // enables the application to access  
      // the configuration file using the 
      // System.Configuration.Configuration class
      ExeConfigurationFileMap configFileMap =
        new ExeConfigurationFileMap();
      configFileMap.ExeConfigFilename = 
        roamingConfig.FilePath;

      // Get the mapped configuration file.
      Configuration config =
        ConfigurationManager.OpenMappedExeConfiguration(
          configFileMap, ConfigurationUserLevel.None);

      try
        {
          currentSection =
               (ConsoleSection)config.GetSection(
                 sectionName);

          // Synchronize the application configuration 
          // if needed. The following two steps seem 
          // to solve some out of synch issues  
          // between roaming and default 
          // configuration.
          config.Save(ConfigurationSaveMode.Modified);

          // Force a reload of the changed section,  
          // if needed. This makes the new values available  
          // for reading.
          ConfigurationManager.RefreshSection(sectionName);

          if (currentSection == null)
          {
            // Create a custom configuration section.
            currentSection = new ConsoleSection();

            // Define where in the configuration file  
            // hierarchy the associated  
            // configuration section can be declared. 
            // The following assignment assures that  
            // the configuration information can be  
            // defined in the user.config file in the  
            // roaming user directory. 
            currentSection.SectionInformation.AllowExeDefinition =
              ConfigurationAllowExeDefinition.MachineToLocalUser;

            // Allow the configuration section to be  
            // overridden by lower-level configuration files. 
            // This means that lower-level files can contain 
            // the section (use the same name) and assign  
            // different values to it as done by the 
            // function GetApplicationConfiguration() in this 
            // example.
            currentSection.SectionInformation.AllowOverride =
              true;

            // Store console settings for roaming users.
            currentSection.ConsoleElement.BackgroundColor =
                ConsoleColor.Blue;
            currentSection.ConsoleElement.ForegroundColor =
                ConsoleColor.Yellow;

            // Add configuration information to  
            // the configuration file.
            config.Sections.Add(sectionName, currentSection);
            config.Save(ConfigurationSaveMode.Modified);
            // Force a reload of the changed section. This  
            // makes the new values available for reading.
            ConfigurationManager.RefreshSection(
              sectionName);
          }
      }
      catch (ConfigurationErrorsException e)
      {
          Console.WriteLine("[Exception error: {0}]",
              e.ToString());
      }

      // Set console properties using values 
      // stored in the configuration file.
      Console.BackgroundColor =
        currentSection.ConsoleElement.BackgroundColor;
      Console.ForegroundColor =
        currentSection.ConsoleElement.ForegroundColor;
      // Apply the changes.
      Console.Clear();

      // Display feedback.
      Console.WriteLine();
      Console.WriteLine(
        "Using OpenExeConfiguration(ConfigurationUserLevel).");
      Console.WriteLine(
          "Configuration file is: {0}", config.FilePath);
    }

    // Get the application configuration file. 
    // This function uses the  
    // OpenExeConfiguration(string)method  
    // to get the application configuration file.  
    // It also creates a custom ConsoleSection and  
    // sets its ConsoleEment BackgroundColor and 
    // ForegroundColor properties to black and white 
    // respectively. Then it uses these properties to 
    // set the console colors.   
    public static void GetAppConfiguration()
    {

      // Get the application path needed to obtain 
      // the application configuration file.
#if DEBUG
      string applicationName =
          Environment.GetCommandLineArgs()[0];
#else 
           string applicationName =
          Environment.GetCommandLineArgs()[0]+ ".exe";
#endif

      string exePath = System.IO.Path.Combine(
          Environment.CurrentDirectory, applicationName);

      // Get the configuration file. The file name has 
      // this format appname.exe.config.
      System.Configuration.Configuration config =
        ConfigurationManager.OpenExeConfiguration(exePath);

      try
      {

        // Create a custom configuration section 
        // having the same name that is used in the  
        // roaming configuration file. 
        // This is because the configuration section  
        // can be overridden by lower-level  
        // configuration files.  
        // See the GetRoamingConfiguration() function in  
        // this example. 
        string sectionName = "consoleSection";
        ConsoleSection customSection = new ConsoleSection();

        if (config.Sections[sectionName] == null)
        {
          // Create a custom section if it does  
          // not exist yet. 

          // Store console settings.
          customSection.ConsoleElement.BackgroundColor =
              ConsoleColor.Black;
          customSection.ConsoleElement.ForegroundColor =
              ConsoleColor.White;

          // Add configuration information to the 
          // configuration file.
          config.Sections.Add(sectionName, customSection);
          config.Save(ConfigurationSaveMode.Modified);
          // Force a reload of the changed section. 
          // This makes the new values available for reading.
          ConfigurationManager.RefreshSection(sectionName);
        }
        // Set console properties using values 
        // stored in the configuration file.
        customSection =
            (ConsoleSection)config.GetSection(sectionName);
        Console.BackgroundColor =
            customSection.ConsoleElement.BackgroundColor;
        Console.ForegroundColor =
            customSection.ConsoleElement.ForegroundColor;
        // Apply the changes.
        Console.Clear();
      }
      catch (ConfigurationErrorsException e)
      {
        Console.WriteLine("[Error exception: {0}]",
            e.ToString());
      }

      // Display feedback.
      Console.WriteLine();
      Console.WriteLine("Using OpenExeConfiguration(string).");
      // Display the current configuration file path.
      Console.WriteLine("Configuration file is: {0}", 
        config.FilePath);
    }

    // Get the AppSettings section.         
    // This function uses the AppSettings property 
    // to read the appSettings configuration  
    // section. 
    public static void ReadAppSettings()
    {
      try
      {
        // Get the AppSettings section.
        NameValueCollection appSettings =
           ConfigurationManager.AppSettings;

        // Get the AppSettings section elements.
        Console.WriteLine();
        Console.WriteLine("Using AppSettings property.");
        Console.WriteLine("Application settings:");

        if (appSettings.Count == 0)
        {
          Console.WriteLine("[ReadAppSettings: {0}]",
          "AppSettings is empty Use GetSection command first.");
        }
        for (int i = 0; i < appSettings.Count; i++)
        {
          Console.WriteLine("#{0} Key: {1} Value: {2}",
            i, appSettings.GetKey(i), appSettings[i]);
        }
      }
      catch (ConfigurationErrorsException e)
      {
        Console.WriteLine("[ReadAppSettings: {0}]",
            e.ToString());
      }
    }

    // Get the ConnectionStrings section.         
    // This function uses the ConnectionStrings  
    // property to read the connectionStrings 
    // configuration section. 
    public static void ReadConnectionStrings()
    {

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

      if (connections.Count != 0)
      {
        Console.WriteLine();
        Console.WriteLine("Using ConnectionStrings property.");
        Console.WriteLine("Connection strings:");

        // Get the collection elements. 
        foreach (ConnectionStringSettings connection in 
          connections)
        {
          string name = connection.Name;
          string provider = connection.ProviderName;
          string connectionString = connection.ConnectionString;

          Console.WriteLine("Name:               {0}", 
            name);
          Console.WriteLine("Connection string:  {0}", 
            connectionString);
         Console.WriteLine("Provider:            {0}", 
            provider);
        }
      }
      else
      {
        Console.WriteLine();
        Console.WriteLine("No connection string is defined.");
        Console.WriteLine();
      }
    }

    // Create the AppSettings section. 
    // The function uses the GetSection(string)method  
    // to access the configuration section.  
    // It also adds a new element to the section collection. 
    public static void CreateAppSettings()
    {
      // Get the application configuration file.
      System.Configuration.Configuration config =
        ConfigurationManager.OpenExeConfiguration(
              ConfigurationUserLevel.None);

      string sectionName = "appSettings";

      // 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. This  
      // makes the new values available for reading.
      ConfigurationManager.RefreshSection(sectionName);

      // Get the AppSettings section.
      AppSettingsSection appSettingSection =
        (AppSettingsSection)config.GetSection(sectionName);

      Console.WriteLine();
      Console.WriteLine("Using GetSection(string).");
      Console.WriteLine("AppSettings section:");
      Console.WriteLine(
        appSettingSection.SectionInformation.GetRawXml());
    }

    // Access the machine configuration file using mapping. 
    // The function uses the OpenMappedMachineConfiguration  
    // method to access the machine configuration.  
    public static void MapMachineConfiguration()
    {
      // Get the machine.config file.
      Configuration machineConfig =
        ConfigurationManager.OpenMachineConfiguration();
      // Get the machine.config file path.
      ConfigurationFileMap configFile =
        new ConfigurationFileMap(machineConfig.FilePath);

      // Map the application configuration file to the machine  
      // configuration file.
      Configuration config =
        ConfigurationManager.OpenMappedMachineConfiguration(
          configFile);

      // Get the AppSettings section.
      AppSettingsSection appSettingSection =
        (AppSettingsSection)config.GetSection("appSettings");
      appSettingSection.SectionInformation.AllowExeDefinition =
          ConfigurationAllowExeDefinition.MachineToRoamingUser;

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

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

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

    }



    // Access a configuration file using mapping. 
    // This function uses the OpenMappedExeConfiguration  
    // method to access a new configuration file.    
    // It also gets the custom ConsoleSection and  
    // sets its ConsoleEment BackgroundColor and 
    // ForegroundColor properties to green and red 
    // respectively. Then it uses these properties to 
    // set the console colors.   
    public static void MapExeConfiguration()
    {

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

      Console.WriteLine(config.FilePath);

      if (config == null)
      {
        Console.WriteLine(
          "The configuration file does not exist.");
        Console.WriteLine(
         "Use OpenExeConfiguration to create the file.");
      }

      // Create a new configuration file by saving  
      // the application configuration to a new file. 
      string appName = 
        Environment.GetCommandLineArgs()[0];

      string configFile =  string.Concat(appName, 
        ".2.config");
      config.SaveAs(configFile, ConfigurationSaveMode.Full);

      // Map the new configuration file.
      ExeConfigurationFileMap configFileMap = 
          new ExeConfigurationFileMap();
      configFileMap.ExeConfigFilename = configFile;

      // Get the mapped configuration file
     config = 
        ConfigurationManager.OpenMappedExeConfiguration(
          configFileMap, ConfigurationUserLevel.None);

      // Make changes to the new configuration file.  
      // This is to show that this file is the  
      // one that is used. 
      string sectionName = "consoleSection";

      ConsoleSection customSection =
        (ConsoleSection)config.GetSection(sectionName);

      if (customSection == null)
      {
          customSection = new ConsoleSection();
          config.Sections.Add(sectionName, customSection);
      }
      else 
          // Change the section configuration values.
          customSection =
              (ConsoleSection)config.GetSection(sectionName);

      customSection.ConsoleElement.BackgroundColor =
          ConsoleColor.Green;
      customSection.ConsoleElement.ForegroundColor =
          ConsoleColor.Red;

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

      // Force a reload of the changed section. This  
      // makes the new values available for reading.
      ConfigurationManager.RefreshSection(sectionName);

      // Set console properties using the  
      // configuration values contained in the  
      // new configuration file.
      Console.BackgroundColor =
        customSection.ConsoleElement.BackgroundColor;
      Console.ForegroundColor =
        customSection.ConsoleElement.ForegroundColor;
      Console.Clear();

      Console.WriteLine();
      Console.WriteLine("Using OpenMappedExeConfiguration.");
      Console.WriteLine("Configuration file is: {0}", 
        config.FilePath);
    }


  }
  #endregion

  #region
  //*** User Interaction Class ***//

  // Obtain user's input and provide feedback. 
  // This class contains the application Main() function. 
  // It calls the ConfigurationManager methods based  
  // on the user's selection. 
  class ApplicationMain
  {
    // Display user's menu. 
    public static void UserMenu()
    {
      string applicationName =
         Environment.GetCommandLineArgs()[0] + ".exe";
      StringBuilder buffer = new StringBuilder();

      buffer.AppendLine("Application: " + applicationName);
      buffer.AppendLine("Please, make your selection.");
      buffer.AppendLine("?    -- Display help.");
      buffer.AppendLine("Q,q  -- Exit the application.");
      buffer.Append("1    -- Use OpenExeConfiguration to get");
      buffer.AppendLine(" the roaming configuration.");
      buffer.Append("        Set console window colors");
      buffer.AppendLine(" to blue and yellow.");
      buffer.Append("2    -- Use GetSection to read or write");
      buffer.AppendLine(" the specified section.");
      buffer.Append("3    -- Use ConnectionStrings property");
      buffer.AppendLine(" to read the section.");
      buffer.Append("4    -- Use OpenExeConfiguration to get");
      buffer.AppendLine(" the application configuration.");
      buffer.Append("        Set console window colors");
      buffer.AppendLine(" to black and white.");
      buffer.Append("5    -- Use AppSettings property");
      buffer.AppendLine(" to read the section.");
      buffer.Append("6    -- Use OpenMappedExeConfiguration");
      buffer.AppendLine(" to get the specified configuration.");
      buffer.Append("        Set console window colors");
      buffer.AppendLine(" to green and red.");
      buffer.Append("7    -- Use OpenMappedMachineConfiguration");
      buffer.AppendLine(" to get the machine configuration.");

      Console.Write(buffer.ToString());
    }

    // Obtain user's input and provide 
    // feedback. 
    static void Main(string[] args)
    {
      // Define user selection string. 
      string selection;

      // Get the name of the application. 
      string appName = 
        Environment.GetCommandLineArgs()[0];


      // Get user selection. 
      while (true)
      {

        UserMenu();
        Console.Write("> ");
        selection = Console.ReadLine();
        if (selection != string.Empty)
          break;
      }

      while (selection.ToLower() != "q")
      { 
        // Process user's input. 
        switch (selection)
        {
          case "1":
            // Show how to use OpenExeConfiguration 
            // using the configuration user level.
            UsingConfigurationManager.GetRoamingConfiguration();
            break;

          case "2":
            // Show how to use GetSection.
            UsingConfigurationManager.CreateAppSettings();
            break;

          case "3":
            // Show how to use ConnectionStrings.
            UsingConfigurationManager.ReadConnectionStrings();
            break;

          case "4":
            // Show how to use OpenExeConfiguration 
            // using the configuration file path.
            UsingConfigurationManager.GetAppConfiguration();
            break;

          case "5":
            // Show how to use AppSettings.
            UsingConfigurationManager.ReadAppSettings();
            break;

          case "6":
            // Show how to use OpenMappedExeConfiguration.
            UsingConfigurationManager.MapExeConfiguration();
            break;

          case "7":
            // Show how to use OpenMappedMachineConfiguration.
            UsingConfigurationManager.MapMachineConfiguration();
            break;

          default:
            UserMenu();
            break;
        }
          Console.Write("> ");
          selection = Console.ReadLine();
      } 
    }
  }
  #endregion

The example works with elements that are similar to the ones illustrated in the following configuration file. These elements are generated the first time that you run the example.


<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="consoleSection" type="Samples.Aspnet.ConsoleSection, 
             ConfigurationManager_CS, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </configSections>
  <appSettings>
        <add key="NewKey0" value="Monday, March 30, 
             2009 1:36:33 PM" />
        <add key="NewKey1" value="Monday, March 30, 
             2009 1:36:40 PM" />
    </appSettings>
  <consoleSection>
        <consoleElement background="Black" foreground="White" />
    </consoleSection>
</configuration>

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

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