標籤:dllimport write oid baidu 方法 檔案中 eval pre eric
C#中讀寫INI檔案
c#的類沒有直接提供對ini檔案的操作支援,可以自己封裝win api的WritePrivateProfileString和GetPrivateProfileString函數實現。下面提供一個封裝類,可以直接使用。
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Runtime.InteropServices; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace ESIMRobotSystem10 {11 class Robot_WriteAndReadInitCls12 {13 public string inipath;14 /// <summary>15 /// 申明INI檔案的寫操作函數16 /// </summary>17 /// <param name="section">INI檔案中的段落</param>18 /// <param name="key">INI檔案中的關鍵字</param>19 /// <param name="val">INI檔案中關鍵字的數值</param>20 /// <param name="filePath">INI檔案的完整的路徑和名稱</param>21 /// <returns></returns>22 [DllImport("kernel32")]23 private static extern long WritePrivateProfileString(24 string section, 25 string key,26 string val, 27 string filePath28 );29 30 /// <summary>31 /// 申明INI檔案的讀操作函數32 /// </summary>33 /// <param name="section">INI檔案中的段落名稱</param>34 /// <param name="key">INI檔案中的關鍵字</param>35 /// <param name="def">無法讀取時候時候的預設數值</param>36 /// <param name="retVal">讀取數值</param>37 /// <param name="size">數值的大小</param>38 /// <param name="filePath">INI檔案的完整路徑和名稱</param>39 /// <returns></returns>40 [DllImport("kernel32")]41 private static extern int GetPrivateProfileString(42 string section, 43 string key, 44 string def, 45 StringBuilder retVal, 46 int size, 47 string filePath48 );49 50 51 /// <summary> 52 /// 構造方法 53 /// </summary> 54 /// <param name="INIPath">檔案路徑</param> 55 public Robot_WriteAndReadInitCls(string INIPath)56 {57 inipath = INIPath;58 }59 60 61 /// <summary> 62 /// 寫入INI檔案 63 /// </summary> 64 /// <param name="Section">項目名稱(如 [TypeName] )</param> 65 /// <param name="Key">鍵</param> 66 /// <param name="Value">值</param> 67 public void IniWriteValue(string Section, string Key, string Value)68 {69 WritePrivateProfileString(Section, Key, Value, this.inipath);70 }71 72 73 /// <summary> 74 /// 讀出INI檔案 75 /// </summary> 76 /// <param name="Section">項目名稱(如 [TypeName] )</param> 77 /// <param name="Key">鍵</param> 78 public string IniReadValue(string Section, string Key)79 {80 StringBuilder temp = new StringBuilder(500);81 int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath);82 return temp.ToString();83 }84 85 86 /// <summary> 87 /// 驗證檔案是否存在 88 /// </summary> 89 /// <returns>布爾值</returns> 90 public bool ExistINIFile()91 {92 return File.Exists(inipath);93 }94 }95 }
C#中讀寫INI檔案