INI就是扩展名为"INI"的文件,其实他本身是个文本文件,可以用记事本打工,主要存放的是用户所做的选择或系统的各种参数.
INI文件其实并不是普通的文本文件.它有自己的结构.由若干段落(SECTION)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键字(KEYWORD)和一个等号,等号右边就是关键字的值(VALUE).例如:
C#命名空间中没有直接读写INI的类,当然如果你把INT当成文本文件用System.IO类来读写算我没说.
我现在介绍的是系统处理INI的方法.
虽然C#中没有,但是在"kernel32.dll"这个文件中有Win32的API函数--WritePrivateProfileString()和GetPrivateProfileString()
C#声明INI文件的写操作函数WritePrivateProfileString():
参数说明:section:INI文件中的段落;key:INI文件中的关键字;val:INI文件中关键字的数值;filePath:INI文件的完整的路径和名称。
C#申明INI文件的读操作函数GetPrivateProfileString():
参数说明:section:INI文件中的段落名称;key:INI文件中的关键字;def:无法读取时候时候的缺省数值;retVal:读取数值;size:数值的大小;filePath:INI文件的完整路径和名称。
下面是一个读写INI文件的类:
读取app.config中自定义配置的值的属性,常用2种方法.
假设有如下配置:
<appSettings>
<add key="A" value="config with A"/>
<add key="B" value="config with B"/>
</appSettings>
using System.Configuration;
[A] 方法
string strTest = ConfigurationSettings.AppSettings["A"]; // get A 's value
[B] 方法
AppSettingsReader appReader = new AppSettingsReader();
string strTest = appReader.GetValue(strKey,typeof(string)).ToString();
假设有如下配置:
<appSettings>
<add key="A" value="config with A"/>
<add key="B" value="config with B"/>
</appSettings>
using System.Configuration;
[A] 方法
string strTest = ConfigurationSettings.AppSettings["A"]; // get A 's value
[B] 方法
AppSettingsReader appReader = new AppSettingsReader();
string strTest = appReader.GetValue(strKey,typeof(string)).ToString();