IniTool.cs 16 KB

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