방법: Web.config 파일에서 응용 프로그램 설정 읽기
업데이트: 2007년 11월
이 예제에서는 Web.config 파일에서 customsetting1 키로 식별되는 응용 프로그램 설정을 읽습니다. appSettings 요소는 문자열의 NameValueCollection 컬렉션입니다. 컬렉션 요소를 사용하는 것이 다른 구성 요소를 사용할 때보다 조금 더 복잡할 수 있습니다.
OpenWebConfiguration 메서드에 null을 전달하여 루트 수준 웹 구성의 구성 설정을 가져올 수 있습니다.
구성 설정을 업데이트하려면 구성 개체의 Save 또는 SaveAs 메서드를 사용합니다. 자세한 내용은 구성 클래스 사용을 참조하십시오. 추가 코드 예제를 보려면 AppSettingsSection 클래스 및 관련 클래스를 참조하십시오.
이 예제에서는 비정적 메서드를 사용하여 구성 데이터를 가져오므로 모든 응용 프로그램에서 구성 데이터를 가져올 수 있습니다. 사용 중인 코드가 있는 응용 프로그램에서 구성 정보를 가져오려면 처리 속도가 빠른 정적 메서드를 사용합니다. 자세한 내용은 ASP.NET 구성 API 개요에서 로컬 및 원격 구성 설정 사용 단원을 참조하십시오.
예제
Dim rootWebConfig1 As System.Configuration.Configuration
rootWebConfig1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Nothing)
If (0 < rootWebConfig1.AppSettings.Settings.Count) Then
Dim customSetting As System.Configuration.KeyValueConfigurationElement
customSetting = rootWebConfig1.AppSettings.Settings("customsetting1")
If Not (Nothing = customSetting.Value) Then
Console.WriteLine("customsetting1 application string = {0}", customSetting.Value)
Else
Console.WriteLine("No customsetting1 application string")
End If
End If
System.Configuration.Configuration rootWebConfig1 =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (0 < rootWebConfig1.AppSettings.Settings.Count)
{
System.Configuration.KeyValueConfigurationElement customSetting =
rootWebConfig1.AppSettings.Settings["customsetting1"];
if (null != customSetting)
Console.WriteLine("customsetting1 application string = \"{0}\"",
customSetting.Value);
else
Console.WriteLine("No customsetting1 application string");
}
코드 컴파일
이 예제에는 다음 사항이 필요합니다.
루트 Web.config 파일에 있는 다음과 같은 형태의 appSettings 요소
<appSettings> <add key="customsetting1" value="Some text here"/> </appSettings>
appSettings 요소는 <configuration> 요소의 직계 자식이며 system.web 요소의 피어입니다.
강력한 프로그래밍
Web.config 파일의 appSettings 요소에서 읽은 값은 항상 String 형식입니다. 지정된 키가 Web.config 파일에 없더라도 오류는 발생하지 않습니다. 대신, 빈 문자열이 반환됩니다.
보안
Windows 보안 설정을 사용하여 구성 파일을 읽을 수 있는 사용자를 제한하는 방법으로 서버의 구성 파일을 보호해야 합니다. 사용자 자격 증명과 같은 중요한 정보는 Web.config 파일의 appSettings 요소에 저장하지 마십시오. 또한 구성 설정을 암호화하는 것이 좋습니다. 자세한 내용은 보호되는 구성을 사용하여 구성 정보 암호화를 참조하십시오.