IniFunction.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Runtime.InteropServices;
  7. using System.IO;
  8. namespace StandardLibrary
  9. {
  10. /// <summary>
  11. /// INI文件操作专用类
  12. /// </summary>
  13. static class IniFile
  14. {
  15. #region API声明
  16. /// <summary>
  17. /// 获取所有段落名称
  18. /// </summary>
  19. /// <param name="lpszReturnBuffer">存放段落名称的内存地址,每个段落之间用\0分隔</param>
  20. /// <param name="nSize">内存大小(characters)</param>
  21. /// <param name="lpFileName">Ini文件</param>
  22. /// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>
  23. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  24. private static extern uint GetPrivateProfileSectionNames(
  25. IntPtr lpszReturnBuffer,
  26. uint nSize,
  27. string lpFileName
  28. );
  29. /// <summary>
  30. /// 获取某个指定段落中所有KEY和Value
  31. /// </summary>
  32. /// <param name="lpAppName">段落名称</param>
  33. /// <param name="lpReturnedString">返回值的内存地址,每个之间用\0分隔</param>
  34. /// <param name="nSize">内存大小(characters)</param>
  35. /// <param name="lpFileName">Ini文件</param>
  36. /// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>
  37. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  38. private static extern uint GetPrivateProfileSection(
  39. string lpAppName,
  40. IntPtr lpReturnedString,
  41. uint nSize,
  42. string lpFileName
  43. );
  44. /// <summary>
  45. /// 读取INI文件中指定的Key的值
  46. /// </summary>
  47. /// <param name="lpAppName">段落名称。如果为null,则读取INI中所有段落名称,每个节点名称之间用\0分隔</param>
  48. /// <param name="lpKeyName">Key名称。如果为null,则读取INI中指定段落中的所有KEY,每个KEY之间用\0分隔</param>
  49. /// <param name="lpDefault">读取失败时的默认值</param>
  50. /// <param name="lpReturnedString">读取的内容缓冲区,读取之后,多余的地方使用\0填充</param>
  51. /// <param name="nSize">内容缓冲区的长度</param>
  52. /// <param name="lpFileName">INI文件名</param>
  53. /// <returns>实际读取到的长度</returns>
  54. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  55. private static extern uint GetPrivateProfileString(
  56. string lpAppName,
  57. string lpKeyName,
  58. string lpDefault,
  59. [In, Out] char[] lpReturnedString,
  60. uint nSize,
  61. string lpFileName
  62. );
  63. //另一种声明方式,使用 StringBuilder 作为缓冲区类型的缺点是不能接受\0字符,会将\0及其后的字符截断,
  64. //所以对于lpAppName或lpKeyName为null的情况就不适用
  65. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  66. private static extern uint GetPrivateProfileString(
  67. string lpAppName,
  68. string lpKeyName,
  69. string lpDefault,
  70. StringBuilder lpReturnedString,
  71. uint nSize,
  72. string lpFileName
  73. );
  74. //再一种声明,使用string作为缓冲区的类型同char[]
  75. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  76. private static extern uint GetPrivateProfileString(
  77. string lpAppName,
  78. string lpKeyName,
  79. string lpDefault,
  80. string lpReturnedString,
  81. uint nSize,
  82. string lpFileName
  83. );
  84. /// <summary>
  85. /// 将指定的键值对写到指定的段落,如果已经存在则替换。
  86. /// </summary>
  87. /// <param name="lpAppName">段落,如果不存在此段落,则创建此段落</param>
  88. /// <param name="lpString">Item键值对,多个用\0分隔,形如key1=value1\0key2=value2
  89. /// <para>如果为string.Empty,则删除指定段落下的所有内容,保留段落</para>
  90. /// <para>如果为null,则删除指定段落下的所有内容,并且删除该段落</para>
  91. /// </param>
  92. /// <param name="lpFileName">INI文件</param>
  93. /// <returns>是否成功写入</returns>
  94. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  95. [return: MarshalAs(UnmanagedType.Bool)] //可以没有此行
  96. private static extern bool WritePrivateProfileSection(
  97. string lpAppName,
  98. string lpString,
  99. string lpFileName
  100. );
  101. /// <summary>
  102. /// 将指定的键和值写到指定的段落,如果已经存在则替换
  103. /// </summary>
  104. /// <param name="lpAppName">段落名称</param>
  105. /// <param name="lpKeyName">键名称。如果为null,则删除指定的段落及其所有的项目</param>
  106. /// <param name="lpString">值内容。如果为null,则删除指定段落中指定的键。</param>
  107. /// <param name="lpFileName">INI文件</param>
  108. /// <returns>操作是否成功</returns>
  109. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  110. [return: MarshalAs(UnmanagedType.Bool)]
  111. private static extern bool WritePrivateProfileString(
  112. string lpAppName,
  113. string lpKeyName,
  114. string lpString,
  115. string lpFileName
  116. );
  117. #endregion
  118. #region 封装
  119. /// <summary>
  120. /// 读取INI文件中的所有段落名称
  121. /// </summary>
  122. /// <param name="iniFile">Ini文件</param>
  123. /// <returns>所有段落,没有内容返回string[0]</returns>
  124. public static string[] INIGetAllSectionNames(string iniFile)
  125. {
  126. uint MAX_BUFFER = 32767; //默认为32767
  127. string[] sections = new string[0]; //返回值
  128. //申请内存
  129. IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
  130. uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFile);
  131. if (bytesReturned != 0)
  132. {
  133. //读取指定内存的内容
  134. string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();
  135. //每个段落之间用\0分隔,末尾有一个\0
  136. sections = local.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
  137. }
  138. //释放内存
  139. Marshal.FreeCoTaskMem(pReturnedString);
  140. return sections;
  141. }
  142. /// <summary>
  143. /// 获取INI文件中指定段落中的所有条目(key=value形式)
  144. /// </summary>
  145. /// <param name="iniFile">Ini文件</param>
  146. /// <param name="section">段落名称</param>
  147. /// <returns>指定段落中的所有条目,没有内容返回string[0]</returns>
  148. public static string[] INIGetAllItems(string iniFile, string section)
  149. {
  150. //返回值形式为 key=value,例如 Color=Red
  151. uint MAX_BUFFER = 32767; //默认为32767
  152. string[] items = new string[0]; //返回值
  153. //分配内存
  154. IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
  155. uint bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, iniFile);
  156. if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
  157. {
  158. string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);
  159. items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
  160. }
  161. Marshal.FreeCoTaskMem(pReturnedString); //释放内存
  162. return items;
  163. }
  164. /// <summary>
  165. /// 获取INI文件中指定段落中的所有条目的Key列表
  166. /// </summary>
  167. /// <param name="iniFile">Ini文件</param>
  168. /// <param name="section">段落名称</param>
  169. /// <returns>如果没有内容,反回string[0]</returns>
  170. public static string[] INIGetAllItemKeys(string iniFile, string section)
  171. {
  172. string[] value = new string[0];
  173. const int SIZE = 1024 * 10;
  174. if (string.IsNullOrEmpty(section))
  175. {
  176. throw new ArgumentException("必须指定段落名称", "section");
  177. }
  178. char[] chars = new char[SIZE];
  179. uint bytesReturned = GetPrivateProfileString(section, null, null, chars, SIZE, iniFile);
  180. if (bytesReturned != 0)
  181. {
  182. value = new string(chars).Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
  183. }
  184. chars = null;
  185. return value;
  186. }
  187. /// <summary>
  188. /// 读取INI文件中指定KEY的字符串型值
  189. /// </summary>
  190. /// <param name="iniFile">Ini文件</param>
  191. /// <param name="section">段落名称</param>
  192. /// <param name="key">键名称</param>
  193. /// <param name="defaultValue">如果没此KEY所使用的默认值</param>
  194. /// <returns>读取到的值</returns>
  195. public static string INIGetStringValue(string iniFile, string section, string key, string defaultValue)
  196. {
  197. string value = defaultValue;
  198. const int SIZE = 1024 * 10;
  199. if (string.IsNullOrEmpty(section))
  200. {
  201. throw new ArgumentException("必须指定段落名称", "section");
  202. }
  203. if (string.IsNullOrEmpty(key))
  204. {
  205. throw new ArgumentException("必须指定键名称", "key");
  206. }
  207. StringBuilder sb = new StringBuilder(SIZE);
  208. uint bytesReturned = GetPrivateProfileString(section, key, defaultValue, sb, SIZE, iniFile);
  209. if (bytesReturned != 0)
  210. {
  211. value = sb.ToString();
  212. }
  213. sb = null;
  214. return value;
  215. }
  216. /// <summary>
  217. /// 在INI文件中,将指定的键值对写到指定的段落,如果已经存在则替换
  218. /// </summary>
  219. /// <param name="iniFile">INI文件</param>
  220. /// <param name="section">段落,如果不存在此段落,则创建此段落</param>
  221. /// <param name="items">键值对,多个用\0分隔,形如key1=value1\0key2=value2</param>
  222. /// <returns></returns>
  223. public static bool INIWriteItems(string iniFile, string section, string items)
  224. {
  225. if (string.IsNullOrEmpty(section))
  226. {
  227. throw new ArgumentException("必须指定段落名称", "section");
  228. }
  229. if (string.IsNullOrEmpty(items))
  230. {
  231. throw new ArgumentException("必须指定键值对", "items");
  232. }
  233. string filePath = iniFile.Remove(iniFile.LastIndexOf("\\"));
  234. if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);
  235. return WritePrivateProfileSection(section, items, iniFile);
  236. }
  237. /// <summary>
  238. /// 在INI文件中,指定段落写入指定的键及值。如果已经存在,则替换。如果没有则创建。
  239. /// </summary>
  240. /// <param name="iniFile">INI文件</param>
  241. /// <param name="section">段落</param>
  242. /// <param name="key">键</param>
  243. /// <param name="value">值</param>
  244. /// <returns>操作是否成功</returns>
  245. public static bool INIWriteValue(string iniFile, string section, string key, string value)
  246. {
  247. if (string.IsNullOrEmpty(section))
  248. {
  249. throw new ArgumentException("必须指定段落名称", "section");
  250. }
  251. if (string.IsNullOrEmpty(key))
  252. {
  253. throw new ArgumentException("必须指定键名称", "key");
  254. }
  255. if (value == null)
  256. {
  257. throw new ArgumentException("值不能为null", "value");
  258. }
  259. string filePath = iniFile.Remove(iniFile.LastIndexOf("\\"));
  260. if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);
  261. return WritePrivateProfileString(section, key, value, iniFile);
  262. }
  263. /// <summary>
  264. /// 在INI文件中,删除指定段落中的指定的键。
  265. /// </summary>
  266. /// <param name="iniFile">INI文件</param>
  267. /// <param name="section">段落</param>
  268. /// <param name="key">键</param>
  269. /// <returns>操作是否成功</returns>
  270. public static bool INIDeleteKey(string iniFile, string section, string key)
  271. {
  272. if (string.IsNullOrEmpty(section))
  273. {
  274. throw new ArgumentException("必须指定段落名称", "section");
  275. }
  276. if (string.IsNullOrEmpty(key))
  277. {
  278. throw new ArgumentException("必须指定键名称", "key");
  279. }
  280. return WritePrivateProfileString(section, key, null, iniFile);
  281. }
  282. /// <summary>
  283. /// 在INI文件中,删除指定的段落。
  284. /// </summary>
  285. /// <param name="iniFile">INI文件</param>
  286. /// <param name="section">段落</param>
  287. /// <returns>操作是否成功</returns>
  288. public static bool INIDeleteSection(string iniFile, string section)
  289. {
  290. if (string.IsNullOrEmpty(section))
  291. {
  292. throw new ArgumentException("必须指定段落名称", "section");
  293. }
  294. return WritePrivateProfileString(section, null, null, iniFile);
  295. }
  296. /// <summary>
  297. /// 在INI文件中,删除指定段落中的所有内容。
  298. /// </summary>
  299. /// <param name="iniFile">INI文件</param>
  300. /// <param name="section">段落</param>
  301. /// <returns>操作是否成功</returns>
  302. public static bool INIEmptySection(string iniFile, string section)
  303. {
  304. if (string.IsNullOrEmpty(section))
  305. {
  306. throw new ArgumentException("必须指定段落名称", "section");
  307. }
  308. return WritePrivateProfileSection(section, string.Empty, iniFile);
  309. }
  310. /// <summary>
  311. /// 在INI文件中,删除所有段落
  312. /// </summary>
  313. /// <param name="iniFile">INI文件</param>
  314. public static bool INIDeleteAll(string iniFile)
  315. {
  316. try
  317. {
  318. string[] section = INIGetAllSectionNames(iniFile);
  319. for (int i = 0; i < section.Length; i++)
  320. {
  321. INIDeleteSection(iniFile, section[i]);
  322. }
  323. return true;
  324. }
  325. catch { return false; }
  326. }
  327. #endregion
  328. }
  329. }