Windows API讀取ini配置文件,今天學到了,寫在這裡供大家分享,希望大家多多拍磚
using System.Runtime.InteropServices;
using System.Text;
namespace CMP_WX
{
/**/
/// <summary>
/// 讀寫ini文件的類
/// 調用kernel32.dll中的兩個API:WritePrivateProfileString,GetPrivateProfileString
/// 來實現對ini 文件的讀寫。
/// INI文件是文本文件,
/// 由若干節(section)組成,
/// 在每個帶括號的標題下面,
/// 是若干個關鍵詞(key)及其對應的值(value)
/// 例如:
/// [Section]
/// Key=value
/// </summary>
public class Read_INT
{
/**/
/// <summary>
/// ini文件名稱(帶路徑)
/// </summary>
public string filePath;
/**/
/// 聲明讀寫INI文件的API函數
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/**/
/// <summary>
/// 類的構造函數
/// </summary>
/// <param name="INIPath">INI文件名</param>
public Read_INT(string INIPath)
{
filePath = INIPath;
}
/**/
/// <summary>
/// 寫INI文件
/// </summary>
/// <param name="Section">Section</param>
/// <param name="Key">Key</param>
/// <param name="value">value</param>
public void WriteInivalue(string Section, string Key, string value)
{
WritePrivateProfileString(Section, Key, value, this.filePath);
}
/**/
/// <summary>
/// 讀取INI文件指定部分
/// </summary>
/// <param name="Section">Section</param>
/// <param name="Key">Key</param>
/// <returns>String</returns>
public string ReadInivalue(string Section, string Key)
{
StringBuilder temp = new StringBuilder(1024);
int i = GetPrivateProfileString(Section, Key, "讀取錯誤", temp, 1024, this.filePath);
return temp.ToString();
}
}
}