ini文件在Win95以前比较盛行,之后由于出册表等技术的出现,ini技术主键退居二线,不过对于一些小项目,读写ini文件还是很适用的。
Windows API提供了读写配置文件的操作,在C#程序中只要导入相应的API即可。例如GetPrivateProfileString()方法,在MSDN查得原型如下:
DWORD GetPrivateProfileString(LPCTSTR lpAppName, // p nameLPCTSTR lpKeyName, // key nameLPCTSTR lpDefault, // default stringLPTSTR lpReturnedString, // destination bufferDWORD nSize, // size of destination bufferLPCTSTR lpFileName // initialization file name
);
由于C#和C++数据类型不同,在导入win32 API时需要做相应的转换,并且要导入相关的类。如下所示:
[DllImport("kernel32")]private static extern int GetPrivateProfileString(string p, string key, string defVal, StringBuilder retVal, int size, string filePath);
同理导入另一个函数
[DllImport("kernel32")]private static extern long WritePrivateProfileString(string p, string key, string val, string filePath)
在main函数测试如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;namespace DoingIni
{class Program{[DllImport("kernel32")]private static extern int GetPrivateProfileString(string p, string key, string defVal, StringBuilder retVal, int size, string filePath);[DllImport("kernel32")]private static extern long WritePrivateProfileString(string p, string key, string val, string filePath);/// <summary> /// 读取INI文件 /// </summary> /// <param name="p">项目名称(如 [p] )</param> /// <param name="skey">键</param> /// <param name="path">路径</param> static string IniReadValue(string p, string skey, string path){StringBuilder temp = new StringBuilder(500);int i = GetPrivateProfileString(p, skey, "", temp, 500, path);return temp.ToString();}/// <summary>/// 写入ini文件/// </summary>/// <param name="p">项目名称</param>/// <param name="key">键</param>/// <param name="value">值</param>/// <param name="path">路径</param>static void IniWrite(string p, string key, string value, string path){WritePrivateProfileString(p, key, value, path);}static void Main(string[] args){IniWrite("上海", "东方明珠", "浦东新区", "f:/test.ini");IniWrite("上海", "上海中心大厦", "浦东新区", "f:/test.ini");IniWrite("湖南", "张家界景区", "张家界", "f:/test.ini");IniWrite("湖南", "凤凰古城", "吉首", "f:/test.ini");IniWrite("湖北", "武当山", "十堰", "f:/test.ini");IniWrite("湖北", "黄鹤楼", "武昌", "f:/test.ini");IniWrite("湖北", "古隆中", "襄阳", "f:/test.ini");IniWrite("江苏", "瘦西湖", "扬州", "f:/test.ini");IniWrite("江苏", "中山陵", "南京", "f:/test.ini");IniWrite("上海", "城隍庙", "浦东新区", "f:/test.ini");string str = IniReadValue("湖南", "凤凰古城", "f:/test.ini");Console.WriteLine(str);IniReadValue("上海", null, "f:/test.ini");删除test.ini文件中A 段落中所有键(没有键,也就没有值了)//IniWrite("A", null, null, "f:/test.ini");删除test.ini文件中所有段落//IniWrite(null, null, null, "f:/test.ini");Console.ReadKey();}}
}
结果如下: