本文对c#使用win32操作ini系统文件做了封装
/// <summary>
/// 利用win32读写ini文件/// </summary>
public class IniFileHelper
{
private readonly string _path;
private const int Capacity = 1024;
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,string key, string value, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,string key, string def, StringBuilder retureValue,int size, string filePath);
public IniFileHelper(string iniPath)
{
_path = iniPath;
}
/// <summary>
/// 向ini文件写
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public string WriteToIniFile(string section, string key, string value)
{
if (File.Exists(_path))
{
return WritePrivateProfileString(section, key, value, this._path).ToString(CultureInfo.InvariantCulture);
}
return "can not find file";
}
/// <summary>
/// 从ini文件读
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <returns></returns>
public string ReadFromIniFile(string section, string key)
{
if (File.Exists(_path))
{
var sb = new StringBuilder(Capacity);
GetPrivateProfileString(section, key, string.Empty, sb, Capacity, this._path);
return sb.ToString();
}
return "can not find file";
}
}