Ini.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. namespace INI
  7. {
  8. public class Ini
  9. {
  10. // 声明INI文件的写操作函数 WritePrivateProfileString()
  11. [System.Runtime.InteropServices.DllImport("kernel32")]
  12. private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
  13. // 声明INI文件的读操作函数 GetPrivateProfileString()
  14. [System.Runtime.InteropServices.DllImport("kernel32")]
  15. private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);
  16. private string sPath = null;
  17. public Ini(string path)
  18. {
  19. this.sPath = path;
  20. }
  21. public void Writue(string section, string key, string value)
  22. {
  23. // section=配置节,key=键名,value=键值,path=路径
  24. WritePrivateProfileString(section, key, value, sPath);
  25. }
  26. public string ReadValue(string section, string key)
  27. {
  28. // 每次从ini中读取多少字节
  29. System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
  30. // section=配置节,key=键名,temp=上面,path=路径
  31. GetPrivateProfileString(section, key, "", temp, 255, sPath);
  32. return temp.ToString();
  33. }
  34. }
  35. class Program
  36. {
  37. static void Main(string[] args)
  38. {
  39. string Current;
  40. Current = Directory.GetCurrentDirectory();//获取当前根目录
  41. Console.WriteLine("Current directory {0}", Current);
  42. // 写入ini
  43. Ini ini = new Ini(Current + "/CoreFS.ini");
  44. //ini.Writue("Setting", "key1", "hello word!");
  45. //ini.Writue("Setting", "key2", "hello ini!");
  46. //ini.Writue("SettingImg", "Path", "IMG.Path");
  47. // 读取ini
  48. string stemp = ini.ReadValue("LABPRINTERADDR", "1");
  49. Console.WriteLine(stemp);
  50. Console.ReadKey();
  51. }
  52. }
  53. }