2024年4月2日发(作者:)

INI文件其实是一种具有特定结构的文本文件,它的构成分为三部分,结构如下:

[Section1]

key 1 = value2

key 1 = value2

……

[Section2]

key 1 = value1

key 2 = value2

……

文件由若干个段落(section)组成,每个段落又分成若干个键(key)和值(value)。Windows

系统自带的Win32的API函数GetPrivateProfileString()和WritePrivateProfileString()分别实

现了对INI文件的读写操作,他们位于下。

但是令人遗憾的是C#所使用的.NET框架下的公共类库并没有提供直接操作INI文件的类,所

以唯一比较理想的方法就是调用API函数。

然后,.Net框架下的类库是基于托管代码的,而API函数是基于非托管代码的,(在运行库的

控制下执行的代码称作托管代码。相反,在运行库之外运行的代码称作非托管代码。)如何实现托管

代码与非托管代码之间的操作呢?.Net框架的pServices命名空间下提

供各种各样支持COM interop及平台调用服务的成员,其中最重要的属性之一DllImportAttribute

可以用来定义用于访问非托管API的平台调用方法,它提供了对从非托管DLL导出的函数进行调用

所必需的信息。下面就来看一下如何实现C#与API函数的互操作。

读操作:

[DllImport("kernel32")]

private static extern int GetPrivateProfileString(string section, string key, string d

efVal, StringBuilder retVal, int size, string filePath);

section:要读取的段落名

key: 要读取的键

defVal: 读取异常的情况下的缺省值

retVal: key所对应的值,如果该key不存在则返回空值

size: 值允许的大小

filePath: INI文件的完整路径和文件名

写操作:

[DllImport("kernel32")]

private static extern long WritePrivateProfileString(string section, string key, strin

g val, string filePath);

section: 要写入的段落名

key: 要写入的键,如果该key存在则覆盖写入

val: key所对应的值

filePath: INI文件的完整路径和文件名

这样,在就可以使用对他们的调用,用常规的方式定义一个名为IniFile类:

1using System;

2using pServices;

3using ;

4

5namespace ng

6

7

{

///

8 /// INI文件的操作类

9 ///

10 public class IniFile

11

13

14 public IniFile(string path)

15 {

16 = path;

17 }

18

19 声明读写INI文件的API函数#region 声明读写INI文件的API函数

20 [DllImport("kernel32")]

21 private static extern long WritePrivateProfileString(string section, string

key, string val, string filePath);

22

23 [DllImport("kernel32")]

24 private static extern int GetPrivateProfileString(string section, string ke

y, string defVal, StringBuilder retVal, int size, string filePath);

25

26 [DllImport("kernel32")]

27 private static extern int GetPrivateProfileString(string section, string ke

y, string defVal, Byte[] retVal, int size, string filePath);

28 #endregion

29

30 ///

{

12 public string Path;