c# 读写ini文件

时间:2021-11-08 06:56:00

//在 Ini 文件中写数据
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

//读取 Ini 文件中的数据
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

/// <summary>
/// 创建Ini文件,并写入数据
/// </summary>
/// <param>根节点</param>
/// <param>键</param>
/// <param>值</param>
/// <param>路径</param>
public static void WriteIniData(string section, string key, string val, string filePath)
{
if (!File.Exists(filePath))
{
var fs = File.Create(filePath);
fs.Dispose();
fs.Close();
}
WritePrivateProfileString(section, key, val, filePath);
}

/// <summary>
/// 读取 Ini 文件
/// </summary>
/// <param>根节点</param>
/// <param>键</param>
/// <param>默认数据</param>
/// <param>返回数据</param>
/// <param>巨细</param>
/// <param>路径</param>
public static void ReadIniData(string section, string key, string def, StringBuilder retVal, int size, string filePath)
{
GetPrivateProfileString(section, key, def, retVal, size, filePath);
}