Dieser Artikel wurde maschinell übersetzt. Wenn Sie die englische Version des Artikels anzeigen möchten, aktivieren Sie das Kontrollkästchen Englisch. Sie können den englischen Text auch in einem Popupfenster anzeigen, indem Sie den Mauszeiger über den Text bewegen.
Übersetzung
Englisch

ConfigurationManager-Klasse

 

Veröffentlicht: Oktober 2016

Stellt Zugriff auf Konfigurationsdateien für Clientanwendungen bereit. Diese Klasse kann nicht vererbt werden.

Namespace:   System.Configuration
Assembly:  System.Configuration (in System.Configuration.dll)

System.Object
  System.Configuration.ConfigurationManager

public static class ConfigurationManager

NameBeschreibung
System_CAPS_pubpropertySystem_CAPS_staticAppSettings

Ruft die AppSettingsSection-Daten für die Standardkonfiguration der aktuellen Anwendung ab.

System_CAPS_pubpropertySystem_CAPS_staticConnectionStrings

Ruft die ConnectionStringsSection-Daten für die Standardkonfiguration der aktuellen Anwendung ab.

NameBeschreibung
System_CAPS_pubmethodSystem_CAPS_staticGetSection(String)

Ruft einen angegebenen Konfigurationsabschnitt für die Standardkonfiguration der aktuellen Anwendung ab.

System_CAPS_pubmethodSystem_CAPS_staticOpenExeConfiguration(ConfigurationUserLevel)

Öffnet die Konfigurationsdatei für die aktuelle Anwendung als Configuration-Objekt.

System_CAPS_pubmethodSystem_CAPS_staticOpenExeConfiguration(String)

Öffnet die angegebene Clientkonfigurationsdatei als Configuration-Objekt.

System_CAPS_pubmethodSystem_CAPS_staticOpenMachineConfiguration()

Öffnet die Computerkonfigurationsdatei auf dem aktuellen Computer als Configuration-Objekt.

System_CAPS_pubmethodSystem_CAPS_staticOpenMappedExeConfiguration(ExeConfigurationFileMap, ConfigurationUserLevel)

Öffnet die angegebene Clientkonfigurationsdatei als Configuration-Objekt mithilfe der angegebenen Dateizuordnung und Benutzerebene.

System_CAPS_pubmethodSystem_CAPS_staticOpenMappedExeConfiguration(ExeConfigurationFileMap, ConfigurationUserLevel, Boolean)

Öffnet die angegebene Clientkonfigurationsdatei als Configuration-Objekt mithilfe der angegebenen Dateizuordnung, Benutzerebene und Vorladeoption.

System_CAPS_pubmethodSystem_CAPS_staticOpenMappedMachineConfiguration(ConfigurationFileMap)

Öffnet die Computerkonfigurationsdatei als Configuration-Objekt, das die angegebene Dateizuordnung verwendet.

System_CAPS_pubmethodSystem_CAPS_staticRefreshSection(String)

Aktualisiert den benannten Abschnitt. Dadurch wird er beim nächsten Abrufen erneut vom Datenträger gelesen.

The T:System.Configuration.ConfigurationManager class enables you to access machine, application, and user configuration information. This class replaces the T:System.Configuration.ConfigurationSettings class, which is deprecated. For web applications, use the T:System.Web.Configuration.WebConfigurationManager class.

To use the T:System.Configuration.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.

System_CAPS_noteHinweis

The name and location of the application configuration file depend on the application's host. For more information, see NIB: Application Configuration Files.

You can use the built-in N: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.

The T:System.Configuration.ConfigurationManager class includes members that enable you to perform the following tasks:

  • Read a section from a configuration file. To access configuration information, call the M:System.Configuration.ConfigurationManager.GetSection(System.String) method. For some sections such as appSettings and connectionStrings, use the P:System.Configuration.ConfigurationManager.AppSettings and P:System.Configuration.ConfigurationManager.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. Use one of the methods provided by the T:System.Configuration.ConfigurationManager class to open a configuration file such as SampleApp.exe.config. These methods return a T:System.Configuration.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:

    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 T:System.Configuration.ConfigurationElement, T:System.Configuration.ConfigurationElementCollection, T:System.Configuration.ConfigurationProperty, and T:System.Configuration.ConfigurationSection classes. For an example of how to extend a built-in configuration type programmatically, see T:System.Configuration.ConfigurationSection. For an example of how to extend a built-in configuration type that uses the attribute-based model, see T:System.Configuration.ConfigurationElement.

Hinweise für Implementierer:

The T:System.Configuration.Configuration class enables programmatic access for editing configuration files. You use one of the Open methods provided by T:System.Configuration.ConfigurationManager. These methods return a T:System.Configuration.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.

To read the configuration files, use M:System.Configuration.Configuration.GetSection(System.String) or M:System.Configuration.Configuration.GetSectionGroup(System.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.

If your application needs read-only access to its own configuration, we recommend that you use the M:System.Configuration.ConfigurationManager.GetSection(System.String) method. This method provides access to the cached configuration values for the current application, which has better performance than the T:System.Configuration.Configuration class.

To write to the configuration files, use one of the Overload:System.Configuration.Configuration.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.

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");
            }
        }
    }
}

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]));
                    }
                }
            }
        }
    }
}

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>

.NET Framework
Verfügbar seit 2.0

Alle öffentlichen statischen Member ( Shared in Visual Basic) dieses Typs sind threadsicher. Die Threadsicherheit für Instanzmember ist nicht garantiert.

Zurück zum Anfang
Anzeigen: