C#中如何读写INI文件
通常C#使用基于XML的配置文件,不过如果有需要的话,比如要兼顾较老的系统,可能还是要用到INI文件。
但C#本身并不具备读写INI文件的API,只有通过调用非托管代码的方式,即系统自身的API才能达到所需的目的。
对应读写的方法分别为GetPrivateProfileString和WritePrivateProfileString。
GetPrivateProfileString中的各参数:
lpAppName —— section的名称
lpKeyName —— key的名称
lpDefault —— 如果lpKeyName没有被找到的话,则将这个值复制到lpReturnedString中
lpReturnedString —— 用于返回结果的值
nSize —— lpReturnedString的字符长度
lpFileName —— INI文件名
WritePrivateProfileString中的各参数:
lpAppName —— section的名称
lpKeyName —— key的名称
lpString —— 与lpKeyName对应的值
lpFileName —— INI文件名
实际代码如下所示:
using System; using System.Runtime.InteropServices; using System.Text; namespace INIDemo { class Program { static void Main(string[] args) { WritePrivateProfileString("Demo", "abc", "123", "c:\\demo.ini"); StringBuilder temp = new StringBuilder(); GetPrivateProfileString("Demo", "abc", "", temp, 255, "c:\\demo.ini"); Console.WriteLine(temp); Console.ReadLine(); } [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool WritePrivateProfileString( string lpAppName, string lpKeyName, string lpString, string lpFileName); [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] private static extern int GetPrivateProfileString( string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName); } }
程序运行后INI文件中的内容为:
[Demo] abc=123
这是一种相对简单的方法,若是不想使用非托管方法,你也可以通过另一种比较麻烦的途径解决这个问题。
由于INI文件的格式是固定的,所以只要编写相应的解析程序就可以完成同样的读写功能,就是通常的字符串处理而已。
如果你不愿亲自动手的话,不要紧,已经有现成的程序——Cinchoo framework,可以为你实现你想作的事情。
然后一切又变得简单了。
原文同步发布于我的个人博客