[C#] 讀寫 INI 檔

  • 1158
  • 0
  • 2016-11-06

[C#] 讀寫 INI 檔

1. 加入參考

using System.Runtime.InteropServices;

2. 調用 win32 API

[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

3. 從 INI 檔中 讀值

string Section = "sectionName";
string FileName = "INI檔名";
string Key = "KeyName";
string Defaut = "";       //如果沒有 Section , 傳回此預設值           
int Size = 255;              //設定回傳 Size 
StringBuilder returnVal = new StringBuilder(255);  //回傳所要接收的值

int ret = GetPrivateProfileString(Section, Key, Defaut, returnVal , Size, FileName);

4. 寫入 INI 檔

string FileName = "檔名";
string Section = "sectionName";
string Key = "KeyName";
string Vaule= "要寫入的值";

WritePrivateProfileString(Section, Key, Vaule, FileName );