IniFiles.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace XdCxRhDW.Sender
  9. {
  10. public static class IniFiles
  11. {
  12. [DllImport("kernel32")]
  13. private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
  14. /// <summary>
  15. /// 读取INI文件
  16. /// </summary>
  17. /// <param name="Section">项名称(如 [TypeName] )</param>
  18. /// <param name="Key">键</param>
  19. public static string ReadValue(string iniFile, string section, string Key, string defaultValue = "")
  20. {
  21. if (!iniFile.Contains(":"))
  22. iniFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, iniFile);
  23. StringBuilder temp = new StringBuilder(50);
  24. GetPrivateProfileString(section, Key, defaultValue, temp, 500, iniFile);
  25. return temp.ToString();
  26. }
  27. /// <summary>
  28. /// 读取INI文件
  29. /// </summary>
  30. /// <param name="Section">项名称(如 [TypeName] )</param>
  31. /// <param name="Key">键</param>
  32. public static T ReadValue<T>(string iniFile, string section, string Key, T defaultValue = default)
  33. {
  34. var strValue = ReadValue(iniFile,section,Key);
  35. if (string.IsNullOrWhiteSpace(strValue))
  36. return defaultValue;
  37. var obj = Convert.ChangeType(strValue, typeof(T));
  38. return (T)obj;
  39. }
  40. }
  41. }