ConfigurationManager.GetSection(String) Method

Definition

Retrieves a specified configuration section for the current application's default configuration.

C#
public static object GetSection(string sectionName);

Parameters

sectionName
String

The configuration section path and name. Node names are separated by forward slashes, for example "system.net/mailSettings/smtp".

Returns

The specified ConfigurationSection object, or null if the section does not exist.

Exceptions

A configuration file could not be loaded.

Examples

The following example shows how to use the GetSection method. The example is part of a larger example that is provided for the ConfigurationManager class.

C#
// 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());
}

Remarks

For client applications, this method retrieves a configuration file obtained by merging the application configuration file, the local user configuration file, and the roaming configuration file.

The GetSection method accesses run-time configuration information that it cannot change. To change the configuration, you use the GetSection method on the configuration file that you obtain by using one of the following methods:

Notes to Inheritors

You must cast the return value to the expected configuration type. To avoid possible casting exceptions, you should use a conditional casting operation such as the as operator in C# or the TryCast function in Visual Basic.

Applies to

Product Versions
.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

See also