C# - 환경 설정 파일 다루기 (app.config)

반응형

 

개요

환경 설정 파일에 사용자가 지정한 키를 저장하여 호출해서 사용 할 수 있습니다.

API KEY 혹은 SECRET EKY 등, 직접적으로 하드 코딩하는 것보다 보안 측면에서 더 안전할 수 있습니다.


app.config 설정

  • 솔루션 탐색기에서 app.config 파일 열기
  • 요소 추가 : <appSettings> </appSettings> 
  • 하위 요소 추가 : <add key="키 값" value="설정 값" />

<!-- app.config -->
<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<startup>
		<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
	</startup>
    
    <!-- Config Setting -->
	<appSettings>
		<add key="test" value="HelloSettingValue" />
	</appSettings>
</configuration>

참조 추가

  • 솔루션 탐색기에서 참조 우클릭 - 참조 추가

 

  • 어셈블리 - System.Configuration 체크 - 확인


환경 설정 값 호출 (ConfigurationManager)

  • ConfigurationManager.AppSettings.Get("키값")
    • App.config 또는 Web.config 파일에서 지정된 키에 대한 값을 검색하는 방법 제공
  • using System.Configuration 추가
    • 추가하지 않으면 ConfigurationManager를 사용 할 수 없음
using System.Configuration;
  • 사용 예시 : "test" 키 호출
// "test" 키 호출
string testing = ConfigurationManager.AppSettings.Get("test");

// "test" 키의 값 출력
MessageBox.Show(testing);


참고

Microsoft - Learn - 문제 해결 - Visual Studio - C# - .config 파일에서 사용자 지정 정보 저장

반응형