Редагувати

Поділитися через


ConfigurationManager Class

Definition

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

public ref class ConfigurationManager abstract sealed
public static class ConfigurationManager
type ConfigurationManager = class
Public Class ConfigurationManager
Inheritance
ConfigurationManager

Examples

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");
            }
        }
    }
}
Imports System.Configuration
Module Module1

    Sub Main()
        ReadAllSettings()
        ReadSetting("Setting1")
        ReadSetting("NotValid")
        AddUpdateAppSettings("NewSetting", "May 7, 2014")
        AddUpdateAppSettings("Setting1", "May 8, 2014")
        ReadAllSettings()
    End Sub

    Sub ReadAllSettings()
        Try
            Dim appSettings = ConfigurationManager.AppSettings

            If appSettings.Count = 0 Then
                Console.WriteLine("AppSettings is empty.")
            Else
                For Each key As String In appSettings.AllKeys
                    Console.WriteLine("Key: {0} Value: {1}", key, appSettings(key))
                Next
            End If
        Catch e As ConfigurationErrorsException
            Console.WriteLine("Error reading app settings")
        End Try
    End Sub

    Sub ReadSetting(key As String)
        Try
            Dim appSettings = ConfigurationManager.AppSettings
            Dim result As String = appSettings(key)
            If IsNothing(result) Then
                result = "Not found"
            End If
            Console.WriteLine(result)
        Catch e As ConfigurationErrorsException
            Console.WriteLine("Error reading app settings")
        End Try
    End Sub

    Sub AddUpdateAppSettings(key As String, value As String)
        Try
            Dim configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
            Dim settings = configFile.AppSettings.Settings
            If IsNothing(settings(key)) Then
                settings.Add(key, value)
            Else
                settings(key).Value = value
            End If
            configFile.Save(ConfigurationSaveMode.Modified)
            ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name)
        Catch e As ConfigurationErrorsException
            Console.WriteLine("Error writing app settings")
        End Try
    End Sub

End Module

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]));
                    }
                }
            }
        }
    }
}
Imports System.Configuration
Imports System.Data.SqlClient
Module Module1

    Sub Main()
        ReadProducts()
    End Sub

    Sub ReadProducts()
        Dim connectionString = ConfigurationManager.ConnectionStrings("WingtipToys").ConnectionString
        Dim queryString = "SELECT Id, ProductName FROM dbo.Products;"
        Using connection As New SqlConnection(connectionString)
            Dim command = New SqlCommand(queryString, connection)
            connection.Open()

            Using reader As SqlDataReader = command.ExecuteReader()
                While reader.Read()
                    Console.WriteLine(String.Format("{0}, {1}", reader(0), reader(1)))
                End While
            End Using
        End Using
    End Sub

End Module

Remarks

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.

Note

The name and location of the application configuration file depend on the application's host. For more information, see Configuring Apps by using 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 Inheritors

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(String) or GetSectionGroup(String). 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(String) 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.

Properties

AppSettings

Gets the AppSettingsSection data for the current application's default configuration.

ConnectionStrings

Gets the ConnectionStringsSection data for the current application's default configuration.

Methods

GetSection(String)

Retrieves a specified configuration section for the current application's default configuration.

OpenExeConfiguration(ConfigurationUserLevel)

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

OpenExeConfiguration(String)

Opens the specified client configuration file as a Configuration object.

OpenMachineConfiguration()

Opens the machine configuration file on the current computer as a Configuration object.

OpenMappedExeConfiguration(ExeConfigurationFileMap, ConfigurationUserLevel, Boolean)

Opens the specified client configuration file as a Configuration object that uses the specified file mapping, user level, and preload option.

OpenMappedExeConfiguration(ExeConfigurationFileMap, ConfigurationUserLevel)

Opens the specified client configuration file as a Configuration object that uses the specified file mapping and user level.

OpenMappedMachineConfiguration(ConfigurationFileMap)

Opens the machine configuration file as a Configuration object that uses the specified file mapping.

RefreshSection(String)

Refreshes the named section so the next time that it is retrieved it will be re-read from disk.

Applies to

See also