.NET Framework Class Library
ConfigurationManager..::.OpenExeConfiguration Method (ConfigurationUserLevel)

Opens the configuration file for the current application as a Configuration object.

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

Visual Basic (Declaration)
Public Shared Function OpenExeConfiguration ( _
    userLevel As ConfigurationUserLevel _
) As Configuration
Visual Basic (Usage)
Dim userLevel As ConfigurationUserLevel
Dim returnValue As Configuration

returnValue = ConfigurationManager.OpenExeConfiguration(userLevel)
C#
public static Configuration OpenExeConfiguration(
    ConfigurationUserLevel userLevel
)
Visual C++
public:
static Configuration^ OpenExeConfiguration(
    ConfigurationUserLevel userLevel
)
JScript
public static function OpenExeConfiguration(
    userLevel : ConfigurationUserLevel
) : Configuration

Parameters

userLevel
Type: System.Configuration..::.ConfigurationUserLevel
The ConfigurationUserLevel for which you are opening the configuration.
Exceptions

ExceptionCondition
ConfigurationErrorsException

A configuration file could not be loaded.

Remarks

Client applications use a global configuration that applies to all users, separate configurations that apply to individual users, and configurations that apply to roaming users. The userLevel parameter determines the location of the configuration file being opened by indicating whether it has no user level (the configuration file is in the same directory as the application) or has a per-user level (the configuration file is in an application settings path determined by the user level).

Specify which configuration to get by passing one of the following values for userLevel:

  • To get the Configuration object that applies to all users, set userLevel to None.

  • To get the local Configuration object that applies to the current user, set userLevel to PerUserRoamingAndLocal.

  • To get the roaming Configuration object that applies to the current user, set userLevel to PerUserRoaming.

    NoteNote:

    To get the Configuration object for a resource, your code must have read permissions on all the configuration files from which it inherits settings. To update a configuration file, your code must additionally have write permissions for both the configuration file and the directory in which it exists.

Examples

The following code example shows how to use the OpenExeConfiguration method.

Visual Basic
' 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 Shared Sub GetRoamingConfiguration()
    ' Define the custom section to add to the
    ' configuration file.
    Dim sectionName As String = "consoleSection"
    Dim currentSection As ConsoleSection = Nothing

    ' Get the roaming configuration 
    ' that applies to the current user.
    Dim roamingConfig As Configuration = _
    ConfigurationManager.OpenExeConfiguration( _
        ConfigurationUserLevel.PerUserRoaming)

    ' Map the roaming configuration file. This
    ' enables the application to access 
    ' the configuration file using the
    ' System.Configuration.Configuration class
    Dim configFileMap As New ExeConfigurationFileMap()
    configFileMap.ExeConfigFilename = _
        roamingConfig.FilePath

    ' Get the mapped configuration file.
    Dim config As Configuration = _
        ConfigurationManager.OpenMappedExeConfiguration( _
            configFileMap, ConfigurationUserLevel.None)

    Try
        currentSection = DirectCast( _
            config.GetSection(sectionName),  _
            ConsoleSection)

        ' 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 Is Nothing Then
            ' 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)
        End If
    Catch e As ConfigurationErrorsException
        Console.WriteLine("[Exception error: {0}]", _
                          e.ToString())
    End Try

    ' 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(userLevel).")
    Console.WriteLine( _
        "Configuration file is: {0}", config.FilePath)
End Sub
C#
// 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);
}
Platforms

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

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0
See Also

Reference

Tags :


Community Content

jlb0002
ArgumentException also Thrown
When calling this method from a web application, an ArgumentException is thrown with the message "exePath must be specified when not running inside a stand alone exe". This makes sense since in a web app, you usually want the web.config, not the app.config.
Tags :

Page view tracker