IniTool.cs 17 KB

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