C# ini (配置文件)API调用以及例子

首先是INI 类例子里面包含了INI用到的API的声明以及 读写两个方法:

 1 public class Ini//文件读写
 2         {
 3             // 声明INI文件的写操作函数 WritePrivateProfileString()
 4 
 5             [System.Runtime.InteropServices.DllImport("kernel32")]
 6 
 7             private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
 8 
 9             // 声明INI文件的读操作函数 GetPrivateProfileString()
10 
11             [System.Runtime.InteropServices.DllImport("kernel32")]
12 
13             private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);
14 
15 
16             private string sPath = null;
17             public Ini(string path)
18             {
19                 this.sPath = path;
20             }
21 
22             public void Writue(string section, string key, string value)
23             {
24 
25                 // section=配置节,key=键名,value=键值,path=路径
26 
27                 WritePrivateProfileString(section, key, value, sPath);
28 
29             }
30             public string ReadValue(string section, string key)
31             {
32 
33                 // 每次从ini中读取多少字节
34 
35                 System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
36 
37                 // section=配置节,key=键名,temp=上面,path=路径
38 
39                 GetPrivateProfileString(section, key, "", temp, 255, sPath);
40 
41                 return temp.ToString();
42 
43             }
44         }

然后是方法调用例子:

            写入:

            string Current;

            Current = Directory.GetCurrentDirectory();//获取当前根目录

            Ini ini = new Ini(Current + "/config.ini");

            ini.Writue(string 标签,string 识别键, value 保存参数);

           读取:

            string Current;

            Current = Directory.GetCurrentDirectory();//获取当前根目录

            Ini ini = new Ini(Current + "/config.ini");

            string a = ini.Readvalue(string 标签,string 识别键);

 

posted @ 2012-11-20 15:56  dongzhaosheng73  阅读(352)  评论(0编辑  收藏  举报