You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.1 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. namespace Shentun.Utilities
  7. {
  8. public class IniFileHelper
  9. {
  10. #region API函数声明
  11. [DllImport("kernel32")]//返回0表示失败,非0为成功
  12. private static extern long WritePrivateProfileString(string section, string key,
  13. string val, string filePath);
  14. [DllImport("kernel32")]//返回取得字符串缓冲区的长度
  15. private static extern long GetPrivateProfileString(string section, string key,
  16. string def, StringBuilder retVal, int size, string filePath);
  17. #endregion
  18. public static string Read(string filePath, string section, string key, string defaultValue)
  19. {
  20. if (File.Exists(filePath))
  21. {
  22. section = section.Trim();
  23. key = key.Trim();
  24. defaultValue = defaultValue.Trim();
  25. StringBuilder temp = new StringBuilder(1024);
  26. GetPrivateProfileString(section, key, defaultValue, temp, 1024, filePath);
  27. string returnValue = temp.ToString().Trim();
  28. return returnValue;
  29. }
  30. else
  31. {
  32. throw new FileNotFoundException(filePath + "文件不存在");
  33. }
  34. }
  35. public static void Write(string filePath, string section, string key, string value)
  36. {
  37. if (File.Exists(filePath))
  38. {
  39. section = section.Trim();
  40. key = key.Trim();
  41. value = value.Trim();
  42. StringBuilder temp = new StringBuilder(1024);
  43. long returnValue = WritePrivateProfileString(section, key, value, filePath);
  44. if (returnValue == 0)
  45. {
  46. throw new Exception("写入" + filePath + "文件数据失败");
  47. }
  48. else
  49. {
  50. return;
  51. }
  52. }
  53. else
  54. {
  55. throw new FileNotFoundException(filePath + "文件不存在");
  56. }
  57. }
  58. }
  59. }