ConfigurationManager Class

定义

提供对客户端应用程序配置文件的访问。 Provides access to configuration files for client applications. 此类不能被继承。 This class cannot be inherited.

public static class ConfigurationManager
继承
ConfigurationManager

示例

第一个示例演示一个简单的控制台应用程序中读取应用程序设置,添加新的设置,并更新现有设置。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  

前面的示例假定你的项目有 App.config 文件,如下所示。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]));  
                    }  
                }  
            }  
        }  
    }  
}  
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  

前面的示例假定你的项目具有 App.config,如下所示。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>  

注解

ConfigurationManager类可以访问计算机、 应用程序和用户的配置信息。The ConfigurationManager class enables you to access machine, application, and user configuration information. 此类替换ConfigurationSettings类,该类已弃用。This class replaces the ConfigurationSettings class, which is deprecated. 对于 web 应用程序使用WebConfigurationManager类。For web applications, use the WebConfigurationManager class.

若要使用ConfigurationManager类中,你的项目必须引用System.Configuration程序集。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.

备注

名称和应用程序配置文件的位置取决于应用程序的主机。The name and location of the application configuration file depend on the application's host. 有关详细信息,请参阅NIB: 应用程序配置文件For more information, see NIB: Application Configuration Files.

可以使用内置System.Configuration类型或派生自它们来处理配置信息。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.

ConfigurationManager类包括成员,您可以执行以下任务:The ConfigurationManager class includes members that enable you to perform the following tasks:

  • 从配置文件中读取的节。Read a section from a configuration file. 若要访问的配置信息,请调用GetSection方法。To access configuration information, call the GetSection method. 对于某些节,如appSettingsconnectionStrings,使用AppSettingsConnectionStrings类。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. 使用提供的方法之一ConfigurationManager类以打开配置文件,例如 SampleApp.exe.config。这些方法返回Configuration反过来公开方法和属性可用来处理关联的配置文件的对象。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:

    除了使用现有配置信息时,可以创建和使用自定义配置元素通过扩展内置的配置类型,如ConfigurationElementConfigurationElementCollectionConfigurationProperty,和ConfigurationSection类。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. 有关如何以编程方式扩展内置的配置类型的示例,请参阅ConfigurationSectionFor an example of how to extend a built-in configuration type programmatically, see ConfigurationSection. 有关如何扩展使用基于属性的模型的内置配置类型的示例,请参阅ConfigurationElementFor an example of how to extend a built-in configuration type that uses the attribute-based model, see ConfigurationElement.

继承者说明

Configuration类,以编辑配置文件以编程方式访问。使用提供的打开方法之一ConfigurationManager。这些方法返回Configuration对象,它又提供所需的方法和属性,以处理基础的配置文件。你可以访问这些文件进行读取或写入。若要读取的配置文件,使用GetSection(String)GetSectionGroup(String)来读取配置信息。读取的进程的用户必须具有以下权限:-读取当前配置层次结构级别上的配置文件的权限。 -读取权限的父配置文件。如果你的应用程序需要其自己的配置只读访问,我们建议你使用GetSection(String)方法。此方法提供访问到当前应用程序的缓存的配置值,它具有更好的性能比Configuration类。若要写入配置文件,请使用其中一个Save方法。写入的进程的用户必须具有以下权限:-配置文件和当前配置层次结构级别上的目录写入权限。 -将读取所有配置文件的权限。

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) 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(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.

属性

AppSettings

获取当前应用程序默认配置的 AppSettingsSection 数据。 Gets the AppSettingsSection data for the current application's default configuration.

ConnectionStrings

获取当前应用程序默认配置的 ConnectionStringsSection 数据。 Gets the ConnectionStringsSection data for the current application's default configuration.

方法

GetSection(String)

检索当前应用程序默认配置的指定配置节。 Retrieves a specified configuration section for the current application's default configuration.

OpenExeConfiguration(ConfigurationUserLevel)

将当前应用程序的配置文件作为 Configuration 对象打开。 Opens the configuration file for the current application as a Configuration object.

OpenExeConfiguration(String)

将指定的客户端配置文件作为 Configuration 对象打开。 Opens the specified client configuration file as a Configuration object.

OpenMachineConfiguration()

将当前计算机上的计算机配置文件作为 Configuration 对象打开。 Opens the machine configuration file on the current computer as a Configuration object.

OpenMappedExeConfiguration(ExeConfigurationFileMap, ConfigurationUserLevel)

可将指定的客户端配置文件作为使用指定文件映射和用户级别的 Configuration 对象打开。 Opens the specified client configuration file as a Configuration object that uses the specified file mapping and user level.

OpenMappedExeConfiguration(ExeConfigurationFileMap, ConfigurationUserLevel, Boolean)

可将指定的客户端配置文件作为使用指定文件映射、用户级别和预加载选项的 Configuration 对象打开。 Opens the specified client configuration file as a Configuration object that uses the specified file mapping, user level, and preload option.

OpenMappedMachineConfiguration(ConfigurationFileMap)

将计算机配置文件作为使用指定文件映射的 Configuration 对象打开。 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.

适用于

另请参阅