IniTool.cs 17 KB

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