使用英语阅读

通过


ConfigurationManager.GetSection(String) 方法

定义

检索当前应用程序默认配置的指定配置节。

public static object GetSection (string sectionName);

参数

sectionName
String

配置节的路径和名称。 节点名称是通过正斜杠分隔开的,例如“system.net/mailSettings/smtp”。

返回

指定的 ConfigurationSection 对象,如果该节不存在,则为 null

例外

无法加载配置文件。

示例

下面的示例显示如何使用 GetSection 方法。 该示例是为 类提供的更大示例的一 ConfigurationManager 部分。

// Create the AppSettings section.
// The function uses the GetSection(string)method 
// to access the configuration section. 
// It also adds a new element to the section collection.
public static void CreateAppSettings()
{
  // Get the application configuration file.
  System.Configuration.Configuration config =
    ConfigurationManager.OpenExeConfiguration(
          ConfigurationUserLevel.None);

  string sectionName = "appSettings";

  // Add an entry to appSettings.
  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.
  config.Save(ConfigurationSaveMode.Modified);
  
  // Force a reload of the changed section. This 
  // makes the new values available for reading.
  ConfigurationManager.RefreshSection(sectionName);

  // Get the AppSettings section.
  AppSettingsSection appSettingSection =
    (AppSettingsSection)config.GetSection(sectionName);

  Console.WriteLine();
  Console.WriteLine("Using GetSection(string).");
  Console.WriteLine("AppSettings section:");
  Console.WriteLine(
    appSettingSection.SectionInformation.GetRawXml());
}

注解

对于客户端应用程序,此方法检索通过合并应用程序配置文件、本地用户配置文件和漫游配置文件获取的配置文件。

方法 GetSection 访问无法更改的运行时配置信息。 若要更改配置,请在 GetSection 使用以下方法之一获取的配置文件上使用 方法:

继承者说明

必须将返回值强制转换为预期的配置类型。 为了避免可能的强制转换异常,应使用条件转换操作,例如 as C# 中的 运算符或 Visual Basic 中的 TryCast 函数。

适用于

产品 版本
.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
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

另请参阅