followyourheart

c#中本身没有读取ini文件的系统方法,需要调用win32的api WritePrivateProfileString和GetPrivateProfileString方法来做读取写入的操作。

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

 

分类:

技术点:

相关文章:

  • 2021-10-15
  • 2022-12-23
  • 2021-08-14
  • 2022-12-23
  • 2021-12-18
  • 2021-09-29
  • 2022-12-23
  • 2021-06-27
猜你喜欢
  • 2021-09-25
  • 2021-11-20
  • 2021-07-04
  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
相关资源
相似解决方案