IniFileClass.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace CCDCount.DLL
  9. {
  10. public class IniFileClass
  11. {
  12. [DllImport("kernel32", CharSet = CharSet.Auto)]
  13. private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
  14. [DllImport("kernel32", CharSet = CharSet.Auto)]
  15. private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
  16. // 通用写入方法
  17. public static void WriteIni<T>(T config, string filePath, string section = "Config")
  18. {
  19. foreach (PropertyInfo prop in typeof(T).GetProperties())
  20. {
  21. object value = prop.GetValue(config);
  22. WritePrivateProfileString(section, prop.Name, value?.ToString() ?? "", filePath);
  23. }
  24. }
  25. // 通用读取方法
  26. public static void ReadIni<T>(ref T config, string filePath, string section = "Config")
  27. {
  28. foreach (var prop in typeof(T).GetProperties())
  29. {
  30. var sb = new StringBuilder(255);
  31. GetPrivateProfileString(section, prop.Name, "", sb, 255, filePath);
  32. if (string.IsNullOrEmpty(sb.ToString())) continue;
  33. try
  34. {
  35. var value = Convert.ChangeType(sb.ToString(), prop.PropertyType);
  36. prop.SetValue(config, value, null);
  37. }
  38. catch (InvalidCastException)
  39. {
  40. // 处理类型转换失败(可扩展日志记录)
  41. }
  42. }
  43. }
  44. }
  45. }