摘要
INI文件是比较常用的配置文件格式,在C#中,没有提供对INI文件直接读写的类库,要想实现INI文件的读写,需要借助Windows API GetPrivateProfileString和WritePrivateProfileString两个方法来实现。
INI写入字符串和整数
借助Windows API,写入字符串和整数类型到INI文件中的参考代码如下:
static class IniWriter
{
[DllImport("kernel32")]
private static extern int WritePrivateProfileString(string section, string key, string val, string filepath);
/// <summary>
/// Write string
/// </summary>
/// <param name="fileName"></param>
/// <param name="Section"></param>
/// <param name="key"></param>
/// <param name="val"></param>
/// <returns></returns>
public static int WriteString(string fileName, string Section, string key, string val)
{
if (!val.StartsWith("\""))
{
val = $"\"{val}\"";
}
return WritePrivateProfileString(Section, key, val, fileName);
}
/// <summary>
/// Write integer
/// </summary>
/// <param name="fileName"></param>
/// <param name="Section"></param>
/// <param name="key"></param>
/// <param name="val"></param>
/// <returns></returns>
public static int WriteInteger(string fileName, string Section, string key, int val)
{
return WritePrivateProfileString(Section, key, val.ToString(), fileName);
}
}
INI读取字符串和整数
与写入字符串和整数类似,从INI文件读取字符串和整数类型的参考代码如下:
static class IniReader
{
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
/// <summary>
/// 读取INI文件指定
/// </summary>
/// <param name="fileName"></param>
/// <param name="Section"></param>
/// <param name="Ident"></param>
/// <param name="Default"></param>
/// <returns></returns>
public static string ReadString(string fileName, string Section, string Ident, string Default)
{
byte[] Buffer = new byte[512];
int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.Length, fileName);
//必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
string s = Encoding.GetEncoding(0).GetString(Buffer);
s = s.Substring(0, bufLen);
return s.Trim();
}
/// <summary>
/// 读整数
/// </summary>
/// <param name="fileName"></param>
/// <param name="Section"></param>
/// <param name="Ident"></param>
/// <param name="Default"></param>
/// <returns></returns>
public static int ReadInteger(string fileName, string Section, string Ident, int Default)
{
string intStr = ReadString(fileName, Section, Ident, Convert.ToString(Default));
try
{
return Convert.ToInt32(intStr);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return Default;
}
}
}
结语
以上给出了借助Windows API在C#中读写INI文件整数和字符串类型的数据,这是比较简单干净的INI读写方法,如果需要更为复杂完善的方法,可以使用三方的INI文件读写库,将在后续的文章中介绍。
评论区