NGMsoftware

NGMsoftware
로그인 회원가입
  • 매뉴얼
  • 학습
  • 매뉴얼

    학습


    C# C# 외부 설정 파일 만들기. (System.Configuration)

    페이지 정보

    본문

    안녕하세요. 엔지엠소프트웨어입니다. C#에는 프로그램을 외부에서 제어할 수 있는 환경 설정 파일과 인터페이스를 제공합니다. .NET에는 2가지의 환경 설정 방법을 제공하는데요. app.config와 Settings.settings입니다. 이 둘의 동작은 유사해 보이지만~ 약간 다르게 동작합니다. 전통적(?)으로 닷넷은 app.config의 appSettings 섹션에 외부에서 제어할 수 있는 값을 처리 해왔습니다. 대표적으로 데이타베이스에 연결하는 "connectionString"과 같은 것들입니다. 프로그램을 배포하는 환경이 달라질 수 있으니 외부에서 데이타베이스에 연결할 수 있는 옵션을 제공하면 프로그램을 다시 빌드(Build) 또는 컴파일(Compile)해서 배포하지 않아도 되기 때문입니다. 그리고, 프로그램 작성 방식에 따라서 실행중인 프로그램을 종료하지 않고도 변경된 설정을 리얼 타임으로 적용시킬수도 있기 때문에 처음에 어떻게 설계하느냐가 중요합니다. Visual Studio에서 프로젝트를 열어보면 app.config 파일이 보일겁니다.

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
      </configSections>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
    </configuration>

     

    app.config는 읽기 전용입니다. 읽기/쓰기를 사용하려면 Settings.settings를 이용해야 합니다. 프로젝트의 속성(Alt+Enter)에 설정 탭에서 사용자 설정을 추가하거나 수정 및 삭제할 수 있습니다. 여기에 Author로 이름을 입력하고, 값에 NGM을 넣어보세요.

    7tmWEaL.png

     

     

    아래 그림과 같이 사용자 설정을 하나 추가 했습니다.

    Ym4HZrs.png

     

     

    app.config 파일을 보면 마지막에 사용자 설정이 추가 된것을 알 수 있습니다.

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
          <section name="MSPC.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
      </configSections>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <userSettings>
        <MSPC.Properties.Settings>
          <setting name="Author" serializeAs="String">
            <value>NGM</value>
          </setting>
        </MSPC.Properties.Settings>
      </userSettings>
    </configuration>

     

     

    사용자 설정은 아래와 같이 접근할 수 있습니다.

    string author = MSPC.Properties.Settings.Default["Author"].ToString();
    MSPC.Properties.Settings.Default["Author"] = "NGMsoftware";
    MSPC.Properties.Settings.Default.Save();
    MSPC.Properties.Settings.Default.Reload();

     

    appSettings 섹션을 직접 추가하고, add 아이템을 추가합니다.

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
          <section name="MSPC.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
      </configSections>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <appSettings>
    	  <add key="connectionString" value="HOST=IP;PORT=5432;USERNAME=postgres;PASSWORD=postgres;DATABASE=postgres" />
      </appSettings>
      <userSettings>
        <MSPC.Properties.Settings>
          <setting name="Author" serializeAs="String">
            <value>NGM</value>
          </setting>
        </MSPC.Properties.Settings>
      </userSettings>
    </configuration>

     

    추가한 내용은 아래와 같습니다.

      <appSettings>
    	  <add key="connectionString" value="HOST=IP;PORT=5432;USERNAME=postgres;PASSWORD=postgres;DATABASE=postgres" />
      </appSettings>

     

    코드에서 이 값을 가져오려면 아래와 같이 System.Configuration을 참조에 추가하고, ConfigurationManager를 사용하세요.

    // POSTGRES 데이타베이스 연결
    string connString = ConfigurationManager.AppSettings["connectionString"];

     

    app.config가 읽기 전용이라고 해서 수정이 불가능한건 아닙니다. 보안이 필요한 섹션은 암호화할 수 있고, 런타임에 프로그래밍적으로 수정도 가능합니다. 또한, 사용자 설정은 프로그램 내부에 캐시되므로 외부로 파일을 배포하지 않아도 됩니다. 그래서 서버 환경에 따라 옵셔널하게 동작해야 하는 경우에는 appSettings를 사용하는게 더 좋은 선택입니다.

     

    이 글이 도움이 되셨다면~ 커피 한잔이라도 후원 부탁드립니다^^

    개발자에게 후원하기

    MGtdv7r.png

     

    추천, 구독, 홍보 꼭~ 부탁드립니다.

    여러분의 후원이 빠른 귀농을 가능하게 해줍니다~ 답답한 도시를 벗어나 귀농하고 싶은 개발자~

    감사합니다~

    • 네이버 공유하기
    • 페이스북 공유하기
    • 트위터 공유하기
    • 카카오스토리 공유하기
    추천0 비추천0

    댓글목록

    등록된 댓글이 없습니다.