我们需要使用API函数来读取INI文件。
1. 建立P/Invoke应用类
在pinvoke.net中查找Win32 API在C#定义。
读取Ini文件的API:GetPrivateProfileString
[DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern uint GetPrivateProfileString( string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName);注意:DllImport属性来自using System.Runtime.InteropServices;
(1)lpAppName
小节名
(2)lpKeyName
键名
(3)lpDefault
缺省值
(4)lpReturnedString
返回值
(5)nSize
返回值长度
(6)lpFileName
读取文件的名称
建立一个公共方法,以供程序使用。
public string readIniFileVal(string iniFileName, string section, string key) { StringBuilder retStrBuilder = new StringBuilder(256); GetPrivateProfileString( section, key, "", retStrBuilder, 256, iniFileName); return retStrBuilder.ToString(); }
Cwin32API.cs
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace callXBFLibrary { class Cwin32API { [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern uint GetPrivateProfileString( string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName); private string iniFileName; public Cwin32API(string fileName) { this.iniFileName = fileName; } /** * <p> Read Ini File Value </p> * * @param name="section" * @param name="key" * @returns string * **/ public string readIniFileVal(string section, string key) { StringBuilder retStrBuilder = new StringBuilder(256); GetPrivateProfileString( section, key, "", retStrBuilder, 256, iniFileName); return retStrBuilder.ToString(); } } }