由于经常要在c#项目中读写ini文件,最好是现成的函数,果然有,记录如下。
1 class Ini 2 { 3 // 声明INI文件的写操作函数 WritePrivateProfileString() 4 [System.Runtime.InteropServices.DllImport("kernel32")] 5 private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); 6 7 // 声明INI文件的读操作函数 GetPrivateProfileString() 8 [System.Runtime.InteropServices.DllImport("kernel32")] 9 private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath); 10 11 private string sPath = null; 12 public Ini(string path) 13 { 14 this.sPath = path; 15 } 16 17 public void Write(string section, string key, string value) 18 { 19 20 // section=配置节,key=键名,value=键值,path=路径 21 WritePrivateProfileString(section, key, value, sPath); 22 23 } 24 public string ReadValue(string section, string key) 25 { 26 27 // 每次从ini中读取多少字节 28 System.Text.StringBuilder temp = new System.Text.StringBuilder(255); 29 30 // section=配置节,key=键名,temp=上面,path=路径 31 GetPrivateProfileString(section, key, "", temp, 255, sPath); 32 33 return temp.ToString(); 34 } 35 }