閱讀英文

共用方式為


Configuration 類別

定義

表示特定電腦、應用程式或資源所適用的組態檔。 此類別無法獲得繼承。

public sealed class Configuration
繼承
Configuration

範例

下列程式代碼範例示範如何使用 Configuration 類別來存取組態檔專案。

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Specialized;

// Before compiling this application, 
// remember to reference the System.Configuration assembly in your project. 
#region CustomSection class

// Define a custom section. This class is used to
// populate the configuration file.
// It creates the following custom section:
//  <CustomSection name="Contoso" url="http://www.contoso.com" port="8080" />.
public sealed class CustomSection : ConfigurationSection
{

    public CustomSection()
    {
    }

    [ConfigurationProperty("name",
     DefaultValue = "Contoso",
     IsRequired = true,
     IsKey = true)]
    public string Name
    {
        get
        {
            return (string)this["name"];
        }
        set
        {
            this["name"] = value;
        }
    }

    [ConfigurationProperty("url",
        DefaultValue = "http://www.contoso.com",
        IsRequired = true)]
    [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
    public string Url
    {
        get
        {
            return (string)this["url"];
        }
        set
        {
            this["url"] = value;
        }
    }

    [ConfigurationProperty("port",
        DefaultValue = (int)8080,
        IsRequired = false)]
    [IntegerValidator(MinValue = 0,
        MaxValue = 8080, ExcludeRange = false)]
    public int Port
    {
        get
        {
            return (int)this["port"];
        }
        set
        {
            this["port"] = value;
        }
    }
}

#endregion

#region Using Configuration Class
class UsingConfigurationClass
{


    // Show how to create an instance of the Configuration class
    // that represents this application configuration file.  
    static void CreateConfigurationFile()
    {
        try
        {

            // Create a custom configuration section.
            CustomSection customSection = new CustomSection();

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

            // Create the custom section entry  
            // in <configSections> group and the 
            // related target section in <configuration>.
            if (config.Sections["CustomSection"] == null)
            {
                config.Sections.Add("CustomSection", customSection);
            }

            // Create and add an entry to appSettings section.
            
            string conStringname="LocalSqlServer";
            string conString = @"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true";
            string providerName="System.Data.SqlClient";

            ConnectionStringSettings connStrSettings = new ConnectionStringSettings();
            connStrSettings.Name = conStringname;
            connStrSettings.ConnectionString= conString;
            connStrSettings.ProviderName = providerName;

            config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);
            
            // Add an entry to appSettings section.
            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.
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Full);

            Console.WriteLine("Created configuration file: {0}",
                config.FilePath);
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateConfigurationFile: {0}", err.ToString());
        }
    }

    // Show how to use the GetSection(string) method.
    static void GetCustomSection()
    {
        try
        {

            CustomSection customSection;

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

            customSection =
                config.GetSection("CustomSection") as CustomSection;

            Console.WriteLine("Section name: {0}", customSection.Name);
            Console.WriteLine("Url: {0}", customSection.Url);
            Console.WriteLine("Port: {0}", customSection.Port);
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("Using GetSection(string): {0}", err.ToString());
        }
    }


    // Show how to use different modalities to save 
    // a configuration file.
    static void SaveConfigurationFile()
    {
        try
        {

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

            // Save the full configuration file and force save even if the file was not modified.
            config.SaveAs("MyConfigFull.config", ConfigurationSaveMode.Full, true);
            Console.WriteLine("Saved config file as MyConfigFull.config using the mode: {0}",
                ConfigurationSaveMode.Full.ToString());

            config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Save only the part of the configuration file that was modified. 
            config.SaveAs("MyConfigModified.config", ConfigurationSaveMode.Modified, true);
            Console.WriteLine("Saved config file as MyConfigModified.config using the mode: {0}",
                ConfigurationSaveMode.Modified.ToString());

            config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Save the full configuration file.
            config.SaveAs("MyConfigMinimal.config");
            Console.WriteLine("Saved config file as MyConfigMinimal.config using the mode: {0}",
                ConfigurationSaveMode.Minimal.ToString());
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("SaveConfigurationFile: {0}", err.ToString());
        }
    }

    // Show how use the AppSettings and ConnectionStrings 
    // properties.
    static void GetSections(string section)
    {
        try
        {

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

            // Get the selected section.
            switch (section)
            {
                case "appSettings":
                    try
                    {
                        AppSettingsSection appSettings =
                            config.AppSettings as AppSettingsSection;
                        Console.WriteLine("Section name: {0}",
                                appSettings.SectionInformation.SectionName);

                        // Get the AppSettings section elements.
                        Console.WriteLine();
                        Console.WriteLine("Using AppSettings property.");
                        Console.WriteLine("Application settings:");
                        // Get the KeyValueConfigurationCollection 
                        // from the configuration.
                        KeyValueConfigurationCollection settings =
                          config.AppSettings.Settings;

                        // Display each KeyValueConfigurationElement.
                        foreach (KeyValueConfigurationElement keyValueElement in settings)
                        {
                            Console.WriteLine("Key: {0}", keyValueElement.Key);
                            Console.WriteLine("Value: {0}", keyValueElement.Value);
                            Console.WriteLine();
                        }
                    }
                    catch (ConfigurationErrorsException e)
                    {
                        Console.WriteLine("Using AppSettings property: {0}",
                            e.ToString());
                    }
                    break;

                case "connectionStrings":
                    ConnectionStringsSection
                        conStrSection =
                        config.ConnectionStrings as ConnectionStringsSection;
                    Console.WriteLine("Section name: {0}",
                        conStrSection.SectionInformation.SectionName);

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

                            // Get the collection elements.
                            foreach (ConnectionStringSettings connection in
                              conStrSection.ConnectionStrings)
                            {
                                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);
                            }
                        }
                    }
                    catch (ConfigurationErrorsException e)
                    {
                        Console.WriteLine("Using ConnectionStrings property: {0}",
                            e.ToString());
                    }
                    break;

                default:
                    Console.WriteLine(
                        "GetSections: Unknown section (0)", section);
                    break;
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("GetSections: (0)", err.ToString());
        }
    }

    // Show how to use the Configuration object properties 
    // to obtain configuration file information.
    static void GetConfigurationInformation()
    {
        try
        {

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

            Console.WriteLine("Reading configuration information:");

            ContextInformation evalContext =
                config.EvaluationContext as ContextInformation;
            Console.WriteLine("Machine level: {0}",
                evalContext.IsMachineLevel.ToString());
                    
            string filePath = config.FilePath;
            Console.WriteLine("File path: {0}", filePath);
             
            bool hasFile = config.HasFile;
            Console.WriteLine("Has file: {0}", hasFile.ToString());

            ConfigurationSectionGroupCollection
                groups = config.SectionGroups;
            Console.WriteLine("Groups: {0}", groups.Count.ToString());
            foreach (ConfigurationSectionGroup group in groups)
            {
                Console.WriteLine("Group Name: {0}", group.Name);
               // Console.WriteLine("Group Type: {0}", group.Type);
            }

            ConfigurationSectionCollection
                sections = config.Sections;
            Console.WriteLine("Sections: {0}", sections.Count.ToString());
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("GetConfigurationInformation: {0}",err.ToString());
        }
    }

#endregion 

#region Application Main
    //*** 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("Make your selection.");
            buffer.AppendLine("?    -- Display help.");
            buffer.AppendLine("Q,q  -- Exit the application.");
            
            buffer.Append("1    -- Instantiate the");
            buffer.AppendLine(" Configuration class.");

            buffer.Append("2    -- Use GetSection(string) to read ");
            buffer.AppendLine(" a custom section.");
            
            buffer.Append("3    -- Use SaveAs methods");
            buffer.AppendLine(" to save the configuration file.");

            buffer.Append("4    -- Use AppSettings property to read");
            buffer.AppendLine(" the appSettings section.");
            buffer.Append("5    -- Use ConnectionStrings property to read");
            buffer.AppendLine(" the connectionStrings section.");

            buffer.Append("6    -- Use Configuration class properties");
            buffer.AppendLine(" to obtain configuration information.");

            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 (!string.IsNullOrEmpty(selection))
                    break;
            }

            while (selection.ToLower() != "q")
            {
                // Process user's input.
                switch (selection)
                {
                    case "1":
                        // Show how to create an instance of the Configuration class.
                        CreateConfigurationFile();
                        break;

                    case "2":
                        // Show how to use GetSection(string) method.
                        GetCustomSection();
                        break;

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

                    case "4":
                        // Show how to use the AppSettings property.
                        GetSections("appSettings");
                        break;

                    case "5":
                        // Show how to use the ConnectionStrings property.
                        GetSections("connectionStrings");
                        break;

                    case "6":
                        // Show how to obtain configuration file information.
                        GetConfigurationInformation();
                        break;

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

}

備註

組態設定會儲存在組態檔的階層中。 類別 Configuration 實例代表套用至特定實體實體的所有組態檔組態設定的合併檢視,例如計算機或邏輯實體,例如應用程式或網站。 邏輯實體可以存在於本機電腦或遠端伺服器上。 如需配置檔的相關信息,請參閱 設定應用程式和ASP.NET 組態檔

當指定的實體沒有組態檔存在時, Configuration 物件代表由 Machine.config 檔案所定義的預設組態設定。

您可以使用下列類別來取得 Configuration 物件:

傳回 Configuration 物件的方法名稱開頭為 「Open」。

您也可以產生組態檔,代表 物件中的 Configuration 組態設定。 若要執行此工作,請使用下列的其中一個方法:

  • Save呼叫 方法來建立新的組態檔。

  • SaveAs呼叫 方法,以在另一個位置產生新的組態檔。

建立組態檔的方法名稱開頭為 「Save」。

注意

若要啟用遠端電腦上的組態設定存取權,請使用 Aspnet_regiis 命令行工具。 如您要此工具的詳細資訊,請參閱 ASP.NET IIS 註冊工具 (Aspnet_regiis.exe) 。 如需建立及存取 .NET Framework 中所含內建區段以外的自定義組態設定的相關信息,請參閱 ConfigurationSection

給繼承者的注意事項

類別 Configuration 提供編輯組態檔的程式設計存取。 您可以使用 Web 應用程式的 類別所提供的 WebConfigurationManager 其中一個「Open」方法,或由用戶端應用程式的 ConfigurationManager 類別提供。 這些方法會傳回 Configuration 物件,接著會提供處理基礎組態檔的方法和屬性。 您可以存取這些檔案來讀取或寫入組態資訊。

您可以使用 GetSection(String) 方法或 GetSectionGroup(String) 方法來讀取組態資訊。 請注意,讀取的使用者或進程必須具有下列許可權:

  • 目前組態階層層級之組態檔的讀取許可權。

  • 所有父組態檔的讀取許可權。

如果您的應用程式需要本身設定的唯讀存取權,建議您針對 Web 應用程式使用 GetSection 方法多載。 針對用戶端應用程式,請使用 GetSection(String) 方法。

這些方法提供目前應用程式的快取組態值存取權,其效能優於 Configuration 類別。

注意:如果您使用採用path參數的靜態 GetSection 方法,path 參數必須參考執行程式碼的應用程式,否則會忽略 參數,並傳回目前執行中應用程式的組態資訊。

您可以使用其中 Save 一種方法來撰寫組態資訊。 請注意,寫入的使用者或進程必須具有下列許可權:

  • 目前組態階層層級之組態檔和目錄的寫入許可權。

  • 所有組態檔的讀取許可權。

屬性

AppSettings

取得此 AppSettingsSection 物件所套用的 Configuration 物件組態區段。

AssemblyStringTransformer

指定用來在組態檔中轉換組件字串的函式委派。

ConnectionStrings

取得此 ConnectionStringsSection 物件所套用的 Configuration 組態區段物件。

EvaluationContext

取得 Configuration 物件的 ContextInformation 物件。

FilePath

取得這個 Configuration 物件所表示的組態檔之實體路徑。

HasFile

取得值,指出這個 Configuration 物件所表示的資源是否有組態檔存在。

Locations

取得這個 Configuration 物件中定義的位置。

NamespaceDeclared

取得或設定值,指出組態檔是否有 XML 命名空間。

RootSectionGroup

取得這個 ConfigurationSectionGroup 物件的根 Configuration

SectionGroups

取得這個組態所定義的區段群組集合。

Sections

取得這個 Configuration 物件所定義的區段集合。

TargetFramework

以目前版本之前的版本為目標時,取得或設定 .NET 的目標版本。

TypeStringTransformer

指定用來在組態檔中轉換型別字串的函式委派。

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetSection(String)

傳回指定的 ConfigurationSection 物件。

GetSectionGroup(String)

取得指定的 ConfigurationSectionGroup 物件。

GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
Save()

將包含在這個 Configuration 物件中的組態設定寫入至目前的 XML 組態檔。

Save(ConfigurationSaveMode, Boolean)

將包含在這個 Configuration 物件中的組態設定寫入至目前的 XML 組態檔。

Save(ConfigurationSaveMode)

將包含在這個 Configuration 物件中的組態設定寫入至目前的 XML 組態檔。

SaveAs(String, ConfigurationSaveMode, Boolean)

將包含在這個 Configuration 物件中的組態設定寫入至指定的 XML 組態檔。

SaveAs(String, ConfigurationSaveMode)

將包含在這個 Configuration 物件中的組態設定寫入至指定的 XML 組態檔。

SaveAs(String)

將包含在這個 Configuration 物件中的組態設定寫入至指定的 XML 組態檔。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

適用於

產品 版本
.NET 8 (package-provided), 9 (package-provided), 10 (package-provided)
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另請參閱