用C#读写ini配置文件

INI就是扩展名为"INI"的文件,其实他本身是个文本文件,可以用记事本打工,主要存放的是用户所做的选择或系统的各种参数. INI文件其实并不是普通的文本文件.它有自己的结构.由若干段落(SECTION)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键字(KEYWORD)和一个等号,等号右边就是关键字的值(VALUE).例如: [Section1] KeyWord1 = Value1 KeyWord2 = Value2 ... [Section2] KeyWord3 = Value3 KeyWord4 = Value4 C#命名空间中没有直接读写INI的类,当然如果你把INT当成文本文件用System.IO类来读写算我没说. 我现在介绍的是系统处理INI的方法. 虽然C#中没有,但是在"kernel32.dll"这个文件中有Win32的API函数--WritePrivateProfileString()和GetPrivateProfileString() C#声明INI文件的写操作函数WritePrivateProfileString():

[DllImport( "kernel32" )] privatestaticexternlong WritePrivateProfileString ( string section ,string key , string val , string filePath ) ;

参数说明:section:INI文件中的段落;key:INI文件中的关键字;val:INI文件中关键字的数值;filePath:INI文件的完整的路径和名称。 C#申明INI文件的读操作函数GetPrivateProfileString():

[DllImport("kernel32")] privatestaticexternint GetPrivateProfileString ( string section , string key , string def , StringBuilder retVal , int size , string filePath ) ;

参数说明:section:INI文件中的段落名称;key:INI文件中的关键字;def:无法读取时候时候的缺省数值;retVal:读取数值;size:数值的大小;filePath:INI文件的完整路径和名称。

原文地址 http://www.cnblogs.com/zzyyll2/archive/2007/11/06/950584.html