본문 바로가기

Server Story..../c#

c# app.config 파일에 저장 및 읽기

App.config 읽고 쓰기

configuration file에 키로 값을 설정해 놓고
필요할 때마다 불러서 쓰면 *.exe.config 설정값만 변경함으로써
프로그램을 좀 더 쉽게 관리할 수 있다.

예전에 COM port 통신 프로그램을 만들면서 포트와 관련된 설정값들을
Configuration 파일을 통해 관리함으로써 따로 디버그 필요없이 *.exe.config 파일만 변경해 사용했다.

app.config 파일을 추가하고 아래의 코드와 같이 <appsettings> 요소에 <add> 요소를 집어넣은 후
메인 소스 코드에서 간단하게 불러오거나 (AppSettingsReader
읽어오고 쓰는 방법(Configuration)을 알아보자


*.exe.config 파일
<configuration>
  <appsettings>
    <add key="appConStr" value="server-localhost;uid='sa';pwd='';database=Cars"/>
    <add key="timesToSayHello" value="8"/>
  </appsettings>
</configuration>


*.cs 파일
using System;
using System.Configuration;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //방법 1
            AppSettingsReader ar = new AppSettingsReader();
            
            //key를 가지고 설정된 value값을 가져온다.
            string str = (string)ar.GetValue("appConStr", typeof(string));
            int numbOfTimes = (int)ar.GetValue("timesToSayHello", typeof(int));

            //방법 2[읽고 쓰기] 
            //before using this code, Add System.Configuration reference
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            //쓰기
            config.AppSettings.Settings["appConStr"].Value = "3";

            //읽기
            string value = ConfigurationManager.AppSettings["appConStr"];

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}


주의할점-
프로그램 개발시 디버그 모드(F5)에는 프로젝트의 Root 폴더에 있는 App.config 파일을 debug/bin 폴더로 복사해 사용한다.

디버그 모드에서 아무리 debug/bin 의 app.config 파일을 고치고 삽질을 해도 다음 디버그 모드때에는 root 폴더의 app.config 파일이 덮어씌우므로 변하지 않는것 처럼 보이는 것이다. Bin 폴더에서 직접 exe를 실행시켜 config 파일을 바꾸어 보면 다음에 프로그램을 실행시켜도 변경한 내용이 적용되어 있는걸 확인할 수 있다.

나처럼 안바뀐다고 성질부리지 말자 -_ㅠ

'Server Story.... > c#' 카테고리의 다른 글

c# 소켓통신 예제.  (0) 2012.04.13
windows command iis ftp 명령어,  (0) 2012.01.18
c# windows Service 등록 방법  (0) 2012.01.03