黑马程序员技术交流社区

标题: C#操作ini配置文件 [打印本页]

作者: 马谦    时间: 2013-10-15 13:57
标题: C#操作ini配置文件
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Text;
  4. using System.IO;
  5. namespace SuperCode.Common
  6. {
  7.   /// <summary>
  8.     /// INI文件读写类。
  9.     /// </summary>
  10. public class INIFile
  11. {
  12. public string path;
  13. public INIFile(string INIPath)
  14. {
  15. path = INIPath;
  16. }

  17. [DllImport("kernel32")]
  18. private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);

  19. [DllImport("kernel32")]
  20. private static extern int GetPrivateProfileString(string section,string key,string def, StringBuilder retVal,int size,string filePath);

  21. [DllImport("kernel32")]
  22. private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);

  23. /// <summary>
  24. /// 写INI文件
  25. /// </summary>
  26. /// <param name="Section"></param>
  27. /// <param name="Key"></param>
  28. /// <param name="Value"></param>
  29. public void IniWriteValue(string Section,string Key,string Value)
  30. {
  31. WritePrivateProfileString(Section,Key,Value,this.path);
  32. }

  33. /// <summary>
  34. /// 读取INI文件
  35. /// </summary>
  36. /// <param name="Section"></param>
  37. /// <param name="Key"></param>
  38. /// <returns></returns>
  39. public string IniReadValue(string Section,string Key)
  40. {
  41. StringBuilder temp = new StringBuilder(255);
  42. int i = GetPrivateProfileString(Section,Key,"",temp, 255, this.path);
  43. return temp.ToString();
  44. }
  45. public byte[] IniReadValues(string section, string key)
  46. {
  47. byte[] temp = new byte[255];
  48. int i = GetPrivateProfileString(section, key, "", temp, 255, this.path);
  49. return temp;

  50. }

  51. /// <summary>
  52. /// 删除ini文件下所有段落
  53. /// </summary>
  54. public void ClearAllSection()
  55. {
  56. IniWriteValue(null,null,null);
  57. }
  58. /// <summary>
  59. /// 删除ini文件下personal段落下的所有键
  60. /// </summary>
  61. /// <param name="Section"></param>
  62. public void ClearSection(string Section)
  63. {
  64. IniWriteValue(Section,null,null);
  65. }
  66. }
  67. }
复制代码

作者: 许庭洲    时间: 2013-10-16 21:08
值得学习ing!
作者: §風過無痕§    时间: 2013-10-17 16:36
学习ing     代码整理一下   




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2