Ini文件十分泛用,先前介紹過python的ini文件讀寫,今天介紹的是C#對ini文件的讀寫。
本文介紹如何在C#實現對ini文件讀寫。
pyhon讀寫ini文件請參考此文。
創建class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
class FileINI:IDisposable { [DllImport("kernal32")] private static extern long WritePrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); [DllImport("kernal32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); private string filepath; private bool bDisposed = false; public FileINI(string filepath) { this.filepath = filepath; } public void WriteIni(string section, string key, string val) { WritePrivateProfileString(section, key, val, filepath); } public void ReadIni(string section, string key) { StringBuilder temp = new StringBuilder(255); GetPrivateProfileString(section, key, "", temp, 255, filepath); return temp.ToString(); } public void Disposed() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool IsDisposing) { if(bDisposed) { return; } if(IsDisposing) {} bDisposed = true; } } |
INI 範例:
1 2 |
[section1] val1=VAL01 |
新建範例:
1 2 3 |
FileINI ini = new FileINI(Application.StartupPath + "\\test.ini"); string iniread = ini.ReadIni("section1", "val1"); ini.WriteIni("section1", "val2", "VAL02"); |
上方程式碼將讀取val1之值(VAL01)存入iniread。
並且將test.ini文件內容改為如下:
1 2 3 |
[section1] val1=VAL01 val2=VAL02 |
留言