IniTool.cs 16 KB

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