C#中讀寫INI文件
阿新 • • 發佈:2017-10-16
ots files inter services urn ons int ipa mes
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 ESIMRobotSystem 10 { 11 class Robot_WriteAndReadInitCls 12 { 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 stringsection, 25 string key, 26 string val, 27 string filePath 28 ); 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 filePath 48 ); 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文件