[C#] WritePrivateProfileString, GetPrivateProfileString in C#

2009. 2. 26. 21:53Coders

출처 : System.Runtime.InteropServices.DllImport

C# 에서 ini 파일에 WriteProfile..., GetProfile... 함수를 사용하는 방법입니다. VC++ 에서는 간단하게 App에서 m_pszProfileName 멤버에 ini 경로를 넣어주면 됐는데, 골치아프죠? 제가 찾았던 건, VC++ 의 해당 함수를 대체하는 C# 코드였는데, 이상한 것만 찾았습니다. ㅠㅠ
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace with_soju.tistory.com
  6. {
  7.     class IniFile
  8.     {
  9.         private string path;
  10.  
  11.         [System.Runtime.InteropServices.DllImport("kernel32")]
  12.         private static extern long WritePrivateProfileString(
  13.             string section, string key, string val, string filePath);
  14.  
  15.         [System.Runtime.InteropServices.DllImport("kernel32")]
  16.         private static extern int GetPrivateProfileString(
  17.             string section, string key, string def,
  18.             StringBuilder retVal, int size, string filePath);
  19.  
  20.         public IniFile(string INIPath)
  21.         {
  22.             path = INIPath;
  23.         }
  24.  
  25.         public void WriteValue(string Section, string Key, string Value)
  26.         {
  27.             WritePrivateProfileString(Section, Key, Value, this.path);
  28.         }
  29.  
  30.         public string ReadValue(string Section, string Key)
  31.         {
  32.             StringBuilder temp = new StringBuilder(255);
  33.             int i = GetPrivateProfileString(
  34.                 Section, Key, string.Empty, temp, 255, this.path);
  35.             return temp.ToString();
  36.         }
  37.     }
  38. }

//사용법은 간단합니다.-초기화(굵은부분은 현재 실행 디렉토리를 가져오는 부분)
IniFile ini = new IniFile(string.Format("{0}\\MyIni.ini", System.Environment.CurrentDirectory));

//읽을 때
string sMyValue = ini.ReadValue("MyProgram", "MySection");

//쓸 때
ini.WriteValue("MyProgram", "MySection", sMyValue);