ConfigurationManager 클래스
어셈블리: System.Configuration(system.configuration.dll)
ConfigurationManager 클래스를 사용하면 컴퓨터, 응용 프로그램 및 사용자 구성 정보에 액세스할 수 있습니다. 이 클래스는 더 이상 사용되지 않는 ConfigurationSettings 클래스 대신 사용됩니다.
클라이언트 응용 프로그램은 클라이언트 컴퓨터에서 실행되지만 웹 응용 프로그램은 클라이언트가 연결되어 있는 서버 컴퓨터에서 실행됩니다.
기본 제공 System.Configuration 형식을 사용하거나 이 형식에서 파생시켜 구성 정보를 처리할 수 있습니다. 이러한 형식을 사용하면 구성 정보 관련 작업을 직접 수행할 수 있으며 사용자 지정 정보를 포함하도록 구성 파일을 확장할 수 있습니다.
ConfigurationManager 클래스에는 다음 작업을 수행할 수 있도록 하는 멤버가 포함되어 있습니다.
-
구성 파일에서 섹션을 읽습니다. 구성 정보에 액세스하려면 GetSection 메서드를 호출합니다. appSettings 및 connectionStrings와 같은 섹션의 경우에는 AppSettings 및 ConnectionStrings 클래스를 사용합니다. 이러한 멤버는 읽기 전용 작업을 수행하고 구성의 캐시된 단일 인스턴스를 사용하며 다중 스레드를 인식합니다.
-
구성 파일을 전체적으로 읽고 씁니다. 응용 프로그램에서 해당 응용 프로그램이나 다른 응용 프로그램 또는 다른 컴퓨터에 대한 모든 수준의 구성 설정을 로컬 또는 원격으로 읽고 쓸 수 있습니다. ConfigurationManager 클래스에서 제공하는 메서드 중 하나를 사용하여 SampleApp.exe.config와 같은 구성 파일을 열 수 있습니다. 이러한 메서드는 Configuration 개체를 반환하며 이 개체는 연결된 구성 파일 관련 작업을 하는 데 사용할 수 있는 메서드와 속성을 노출합니다. 또한 이러한 메서드는 읽기 또는 쓰기 작업을 수행하고 파일이 쓰여질 때마다 구성 데이터를 다시 만듭니다.
-
구성 작업을 지원합니다. 다음 형식은 다양한 구성 작업을 지원하는 데 사용됩니다.
기존 구성 정보 관련 작업을 수행하는 것 외에도 ConfigurationElement, ConfigurationElementCollection, ConfigurationProperty 및 ConfigurationSection 클래스와 같은 기본 제공 구성 형식을 확장하여 사용자 지정 구성 요소를 만들고 관련 작업을 수행할 수 있습니다. 기본 제공 구성 형식을 프로그래밍 방식으로 확장하는 방법에 대한 예제를 보려면 ConfigurationSection을 참조하십시오. 특성 기반 모델을 사용하여 기본 제공 구성 형식을 확장하는 방법에 대한 예제를 보려면 ConfigurationElement를 참조하십시오.
-
현재 구성 계층 구조 수준의 구성 파일에 대한 읽기 권한
-
모든 부모 구성 파일에 대한 읽기 권한
-
현재 구성 계층 구조 수준의 구성 파일과 디렉터리에 대한 쓰기 권한
-
모든 구성 파일에 대한 읽기 권한
다음 코드 예제에서는 ConfigurationManager 클래스를 사용하여 appSettings 구성 섹션에 액세스하는 방법을 보여 줍니다. 섹션이 없으면 만들어져 구성 파일에 추가됩니다.
using System; using System.Collections.Specialized; using System.Collections.ObjectModel; using System.Collections; using System.Text; using System.Configuration; namespace Samples.AspNet { class UsingConfigurationManager { // Show how to use AppSettings. static void DisplayAppSettings() { // Get the AppSettings collection. NameValueCollection appSettings = ConfigurationManager.AppSettings; string[] keys = appSettings.AllKeys; Console.WriteLine(); Console.WriteLine("Application appSettings:"); // Loop to get key/value pairs. for (int i = 0; i < appSettings.Count; i++) Console.WriteLine("#{0} Name: {1} Value: {2}", i, keys[i], appSettings[i]); } // Show how to use ConnectionStrings. static void DisplayConnectionStrings() { // Get the ConnectionStrings collection. ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings; Console.WriteLine(); Console.WriteLine("Connection strings:"); // Loop to get the collection elements. IEnumerator conEnum = connections.GetEnumerator(); int i = 0; while (conEnum.MoveNext()) { string name = connections[i].Name; string connectionString = connections[name].ConnectionString; string provider = connections[name].ProviderName; Console.WriteLine("Name: {0}", name); Console.WriteLine("Connection string: {0}", connectionString); Console.WriteLine("Provider: {0}", provider); } } // Show how to use OpenMachineConfiguration. static void DisplayMachineConfigSections() { // Get the machine.config file. Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration(); ConfigurationSectionCollection sections = machineConfig.Sections; Console.WriteLine(); Console.WriteLine("Sections in machine.config:"); // Loop to get the sections machine.config. foreach (ConfigurationSection section in sections) { string name = section.SectionInformation.Name; Console.WriteLine("Name: {0}", name); } } // Show how to use OpenExeConfiguration(ConfigurationUserLevel) // and RefreshSection. static void UpdateAppSettings() { // Get the configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); // 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. ConfigurationManager.RefreshSection("appSettings"); } // Show how to use OpenExeConfiguration(string). static void DisplayAppSettingsRawXml() { // Get the application path. string exePath = System.IO.Path.Combine( Environment.CurrentDirectory, "ConfigurationManager.exe"); // Get the configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(exePath); // Get the AppSetins section. AppSettingsSection appSettingSection = config.AppSettings; // Display raw xml. Console.WriteLine(appSettingSection.SectionInformation.GetRawXml()); } // Show how to use GetSection. static void DisplayAppSettingsSectionRawXml() { // Get the configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Get the AppSetins section. AppSettingsSection appSettingSection = (AppSettingsSection)config.GetSection("appSettings"); // Display raw xml. Console.WriteLine(appSettingSection.SectionInformation.GetRawXml()); } // Show how to use OpenMappedMachineConfiguration. static void DisplayMappedMachineConfigurationFileSections() { // Get the machine.config file. Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration(); // Map to the machine configuration file. ConfigurationFileMap configFile = new ConfigurationFileMap(machineConfig.FilePath); Configuration config = ConfigurationManager.OpenMappedMachineConfiguration(configFile); // Display the configuration file sections. ConfigurationSectionCollection sections = config.Sections; Console.WriteLine(); Console.WriteLine("Sections in machine.config:"); // Loop to get the sections machine.config. foreach (ConfigurationSection section in sections) { string name = section.SectionInformation.Name; Console.WriteLine("Name: {0}", name); } } // Show how to use OpenMappedExeConfiguration. static void DisplayMappedExeConfigurationFileSections() { // Get the application configuration file path. string exeFilePath = System.IO.Path.Combine( Environment.CurrentDirectory, "ConfigurationManager.exe.config"); // Map to the application configuration file. ExeConfigurationFileMap configFile = new ExeConfigurationFileMap(); configFile.ExeConfigFilename = exeFilePath; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None); // Display the configuration file sections. ConfigurationSectionCollection sections = config.Sections; Console.WriteLine(); Console.WriteLine("Sections in machine.config:"); // Loop to get the sections machine.config. foreach (ConfigurationSection section in sections) { string name = section.SectionInformation.Name; Console.WriteLine("Name: {0}", name); } } static void Main(string[] args) { // Show how to use OpenExeConfiguration() and RefreshSection. UpdateAppSettings(); // Show how to use AppSettings. DisplayAppSettings(); // Show how to use ConnectionStrings. DisplayConnectionStrings(); // Show how to use OpenExeConfiguration(string). DisplayAppSettingsRawXml(); // Show how to use GetSection. DisplayAppSettingsSectionRawXml(); // Show how to use OpenMappedMachineConfiguration. DisplayMappedMachineConfigurationFileSections(); // Show how to use OpenMappedExeConfiguration. DisplayMappedExeConfigurationFileSections(); // Show how to use OpenMachineConfiguration. DisplayMachineConfigSections(); } } }
이 예제에서는 예제를 처음 실행할 때 생성되는 다음 구성 파일에 나와 있는 요소와 관련된 작업을 합니다.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="NewKey0" value="Monday, January 23, 2006 2:56:14 PM" />
<add key="NewKey1" value="Monday, January 23, 2006 3:15:18 PM" />
<add key="NewKey2" value="Monday, January 23, 2006 3:16:29 PM" />
</appSettings>
</configuration>
Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
Microsoft .NET Framework 3.0은 Windows Vista, Microsoft Windows XP SP2 및 Windows Server 2003 SP1에서 지원됩니다.