INI文件配置乱码——C#

在声明时加上参数CharSet = CharSet.Unicode

[DllImport("kernel32", CharSet = CharSet.Unicode)]

CharSet: 指示如何向方法封送字符串参数,并控制名称重整。

最后,附上读写ini文件,解决出现乱码的代码

[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        
/// <summary>
///读取ini文件数据
/// </summary>
/// <param name="Section"></param>
/// <param name="Key">键名</param>
/// <param name="def">默认值</param>
/// <param name="filePath">文件路径</param>
/// <returns>读出内容</returns>
public static string ReadValueFromIniFile(string Section, string Key, string def, string filePath)
{
    StringBuilder temp = new StringBuilder(4096);
    int i = GetPrivateProfileString(Section, Key, def, temp, 4096, filePath);
    return temp.ToString();
}
 
/// <summary>
/// 写入数据到ini文件
/// </summary>
/// <param name="Section"></param>
/// <param name="Key">键名</param>
/// <param name="Value">键值</param>
/// <param name="filePath">文件路径</param>
public static void WriteValueFromIniFile(string Section, string Key, string Value, string filePath)
{
    WritePrivateProfileString(Section, Key, Value, filePath);
}

 

posted @ 2021-01-05 10:08  vv彭  阅读(3014)  评论(1编辑  收藏  举报