INIHelper.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. namespace ZLPlugin_LisPacs_MR
  7. {
  8. public class INIHelper
  9. {
  10. [DllImport("kernel32")]
  11. public static extern bool WritePrivateProfileString(byte[] section, byte[] key, byte[] val, string filePath);
  12. [DllImport("kernel32")]
  13. public static extern int GetPrivateProfileString(byte[] section, byte[] key, byte[] def, byte[] retVal, int size, string filePath);
  14. private static string fileName = "C:/APPSOFT/PUBLIC/LisPacsConfig.ini";
  15. public static bool WriteString(string section, string key, string value, string encodingName = "utf-8")
  16. {
  17. return WritePrivateProfileString(
  18. getBytes(section, encodingName),
  19. getBytes(key, encodingName),
  20. getBytes(value, encodingName),
  21. fileName);
  22. }
  23. //与ini交互必须统一编码格式
  24. private static byte[] getBytes(string s, string encodingName)
  25. {
  26. return null == s ? null : Encoding.GetEncoding(encodingName).GetBytes(s);
  27. }
  28. public static string ReadString(string section, string key, string def, string encodingName = "utf-8", int size = 256)
  29. {
  30. byte[] buffer = new byte[size];
  31. int count = GetPrivateProfileString(
  32. getBytes(section, encodingName),
  33. getBytes(key, encodingName),
  34. getBytes(def, encodingName),
  35. buffer,
  36. size,
  37. fileName);
  38. return Encoding.GetEncoding(encodingName).GetString(buffer, 0, count).Trim();
  39. }
  40. }
  41. }