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 string section, 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 }