IniTool.cs 17 KB

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