ConfigurationManager 類別

定義

提供用戶端應用程式的組態檔存取。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
繼承
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. 如需詳細資訊,請參閱使用設定檔設定應用程式For more information, see Configuring Apps by using 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),請AppSettings使用ConnectionStrings和類別。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。這些方法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:

    除了使用現有的設定資訊之外,您還可以藉由擴充內建的設定類型( ConfigurationElement例如、 ConfigurationElementCollectionConfigurationPropertyConfigurationSection類別)來建立及使用自訂設定元素。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. 如需如何以程式設計方式擴充內建設定類型的範例,請ConfigurationSection參閱。For 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類別可讓您以程式設計方式存取編輯設定檔。The Configuration class enables programmatic access for editing configuration files. 您可以使用所提供ConfigurationManager的其中一個 Open 方法。You use one of the Open methods provided by ConfigurationManager. 這些方法Configuration會傳回物件,接著提供必要的方法和屬性來處理基礎的設定檔。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.

若要讀取設定檔,請GetSection(String)使用GetSectionGroup(String)或來讀取設定資訊。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.

如果您的應用程式需要唯讀存取自己的設定, GetSection(String)建議您使用方法。If your application needs read-only access to its own configuration, we recommend that you use the GetSection(String) method. 這個方法可讓您存取目前應用程式的快取設定值,其效能高於Configuration類別。This method provides access to the cached configuration values for the current application, which has better performance than the Configuration class.

若要寫入設定檔案,請使用其中一Save種方法。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.

適用於

另請參閱