Configuration.GetSection(String) 方法

定義

傳回指定的 ConfigurationSection 物件。

public:
 System::Configuration::ConfigurationSection ^ GetSection(System::String ^ sectionName);
public System.Configuration.ConfigurationSection GetSection (string sectionName);
member this.GetSection : string -> System.Configuration.ConfigurationSection
Public Function GetSection (sectionName As String) As ConfigurationSection

參數

sectionName
String

要傳回的區段之路徑。

傳回

指定的 ConfigurationSection 物件;如果要求的區段不存在,則為 null

範例

下列範例示範如何使用 GetSection 方法來存取自定義區段。 如需定義類別以儲存區段資訊 CustomSection 的完整範例程式代碼,請參閱 Configuration 類別概觀。

// 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 the GetSection(string) method.
Public Shared Sub GetCustomSection()
    Try

        Dim customSection As CustomSection

        ' Get the current configuration file.
        Dim config As System.Configuration.Configuration = TryCast(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None), Configuration)

        customSection = TryCast(config.GetSection("CustomSection"), CustomSection)

        Console.WriteLine("Section name: {0}", customSection.Name)
        Console.WriteLine("Url: {0}", customSection.Url)
        Console.WriteLine("Port: {0}", customSection.Port)

    Catch err As ConfigurationErrorsException
        Console.WriteLine("Using GetSection(string): {0}", err.ToString())
    End Try

End Sub

備註

組態設定包含在區段中,以方便起見將類似的設定分組在一起。 方法 GetSection 會依其名稱擷取組態區段。

適用於