使用INI配置文件,简单便捷。
该辅助工具类为C#操作INI文件的辅助类,源码在某位师傅的基础上完善的来,因为忘记最初的来源了,因此不能提及引用,在此深感遗憾,并对贡献者表示感谢。
1 using System; 2 using System.Collections; 3 using System.Collections.Generic; 4 using System.Runtime.InteropServices; 5 using System.Text; 6 7 namespace Eyuan.Common 8 { 9 public static class INIHelper 10 { 11 12 #region 读写INI文件相关 13 [DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString", CharSet = CharSet.Ansi)] 14 private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); 15 16 [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString", CharSet = CharSet.Ansi)] 17 private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); 18 19 [DllImport("kernel32")] 20 private static extern int GetPrivateProfileInt(string lpApplicationName, string lpKeyName, int nDefault, string lpFileName); 21 22 23 [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileSectionNames", CharSet = CharSet.Ansi)] 24 private static extern int GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, int nSize, string filePath); 25 26 [DllImport("KERNEL32.DLL ", EntryPoint = "GetPrivateProfileSection", CharSet = CharSet.Ansi)] 27 private static extern int GetPrivateProfileSection(string lpAppName, byte[] lpReturnedString, int nSize, string filePath); 28 #endregion 29 30 #region 读写操作(字符串) 31 /// <summary> 32 /// 向INI写入数据 33 /// </summary> 34 /// <PARAM name="Section">节点名</PARAM> 35 /// <PARAM name="Key">键名</PARAM> 36 /// <PARAM name="Value">值(字符串)</PARAM> 37 public static void Write(string Section, string Key, string Value, string path) 38 { 39 WritePrivateProfileString(Section, Key, Value, path); 40 } 41 /// <summary> 42 /// 读取INI数据 43 /// </summary> 44 /// <PARAM name="Section">节点名</PARAM> 45 /// <PARAM name="Key">键名</PARAM> 46 /// <PARAM name="Path">值名</PARAM> 47 /// <returns>值(字符串)</returns> 48 public static string Read(string Section, string Key, string path) 49 { 50 StringBuilder temp = new StringBuilder(255); 51 int i = GetPrivateProfileString(Section, Key, "", temp, 255, path); 52 return temp.ToString(); 53 } 54 #endregion 55 56 #region 配置节信息 57 /// <summary> 58 /// 读取一个ini里面所有的节 59 /// </summary> 60 /// <param name="sections"></param> 61 /// <param name="path"></param> 62 /// <returns>-1:没有节信息,0:正常</returns> 63 public static int GetAllSectionNames(out string[] sections, string path) 64 { 65 int MAX_BUFFER = 32767; 66 IntPtr pReturnedString = Marshal.AllocCoTaskMem(MAX_BUFFER); 67 int bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, path); 68 if (bytesReturned == 0) 69 { 70 sections = null; 71 return -1; 72 } 73 string local = Marshal.PtrToStringAnsi(pReturnedString, (int)bytesReturned).ToString(); 74 Marshal.FreeCoTaskMem(pReturnedString); 75 //use of Substring below removes terminating null for split 76 sections = local.Substring(0, local.Length - 1).Split('