INI文件在系统配置及应用程序参数保存与设置方面,具有很重要的作用,TSVN的配置文件就是使用INI存储的,下面我们介绍下使用C#读写INI文件的整体思路。
封装WindowAPI
首先,读写INI文件需要用到WindowsAPI中的WritePrivateProfileString与GetPrivateProfileString方法,然而怎么在C#中调用这两个方法呢?
C#提供了DllImportAttribute属性,可将该属性应用于方法,该属性提供对从非托管 DLL 导出的函数进行调用所必需的信息。作为最低要求,必须提供包含入口点的 DLL 的名称。
在此,我们需要调用包含上文提到的两个读写INI文件方法的DLL(kernel32),语法如下:[DllImport("kernel32")]。
然后根据API需要的参数对两个方法进行封装。我们将其封装在IniAccessor类中,封装完毕的方法为:
1. WritePrivateProfileString
[DllImport("kernel32")]
internal static extern long WritePrivateProfileString(string section, string key, string value, string filePath);
参数说明:
2. GetPrivateProfileString
[DllImport("kernel32")]
internal static extern long GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder refValue, int size, string filePath);
参数说明:
注意:用 DllImport 属性修饰的方法必须具有 extern 修饰符。
C#中调用并封装为IniFile类
1.写入一个配置节
public bool IniWriteValue(string section, string key, string value)
{
if (IniAccessor.WritePrivateProfileString(section, key, value, _path) != 0)
return true;
else
return false;
}
2.读取一个配置节
public string IniReadValue(string section, string key)
{
StringBuilder value = new StringBuilder(255);
IniAccessor.GetPrivateProfileString(section, key, null, value, 255, _path);
return value.ToString();
}
调用实例
下面的代码是在config文件中的miscellany配置节下,添加enable-auto-props=yes属性。
private static void EnableAutoProps()
{
string filePath = @"C:\config";
string section = "miscellany";
string key = "enable-auto-props";
IniFile iniFile = new IniFile(filePath);
iniFile.IniWriteValue(section, key, "yes");
}
其中IniFile类内封装了读取及写入方法,且在初始化时,已将INI文件路径传入,以便后续的读写操作。