我們需要使用API函數來讀取INI文件。
1. 建立P/Invoke應用類
在pinvoke.net中查找Win32 API在C#定義。
讀取Ini文件的API:GetPrivateProfileString<喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PHByZSBjbGFzcz0="brush:java;">[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(); }
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); public string readIniFileVal(string iniFileName, string section, string key) { StringBuilder retStrBuilder = new StringBuilder(256); GetPrivateProfileString( section, key, "", retStrBuilder, 256, iniFileName); return retStrBuilder.ToString(); } } }