Iniconfig.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Text;
  3. using System.IO;
  4. using System.Runtime.InteropServices;
  5. public class Iniconfig
  6. {
  7. public class OperateIniFile
  8. {
  9. #region API函数声明
  10. [DllImport("kernel32")]//返回0表示失败,非0为成功
  11. private static extern long WritePrivateProfileString(string section, string key,
  12. string val, string filePath);
  13. [DllImport("kernel32")]//返回取得字符串缓冲区的长度
  14. private static extern long GetPrivateProfileString(string section, string key,
  15. string def, StringBuilder retVal, int size, string filePath);
  16. #endregion
  17. /// <summary>
  18. /// 读Ini文件
  19. /// </summary>
  20. /// <param name="Section">[]内的段落名</param>
  21. /// <param name="Key">key</param>
  22. /// <param name="NoText"></param>
  23. /// NoText对应API函数的def参数,它的值由用户指定,是当在配置文件中没有找到具体的Value时,就用NoText的值来代替。可以为空
  24. /// <param name="iniFilePath">ini配置文件的路径加ini文件名</param>
  25. /// <returns></returns>
  26. #region 读Ini文件
  27. public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
  28. {
  29. if (File.Exists(iniFilePath))
  30. {
  31. StringBuilder temp = new StringBuilder(1024);
  32. GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
  33. return temp.ToString();
  34. }
  35. else
  36. {
  37. return String.Empty;
  38. }
  39. }
  40. #endregion
  41. #region 写Ini文件
  42. public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
  43. {
  44. if (File.Exists(iniFilePath))
  45. {
  46. long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
  47. if (OpStation == 0)
  48. {
  49. return false;
  50. }
  51. else
  52. {
  53. return true;
  54. }
  55. }
  56. else
  57. {
  58. return false;
  59. }
  60. }
  61. #endregion
  62. }
  63. }