c# 解决ini中文乱码
乱码仅仅是因为编码规则导致
解码时对应文件的码制即可
public class IniConfig
{
private string inipath = AppDomain.CurrentDomain.BaseDirectory + "Config.ini";
public bool CanRead()
{
if (File.Exists(inipath))
{
return true;
}
return false;
}
//声明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, byte[] retVal, int size, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/// <summary>
/// 写入INI文件
/// </summary>
public void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.inipath);
}
/// <summary>
/// 读出INI文件
/// </summary>
public string IniReadValue(string Section, string Key, Encoding encoding)
{
try
{
byte[] Buffer = new byte[500];
int bufLen = GetPrivateProfileString(Section, Key, "", Buffer, Buffer.GetUpperBound(0), this.inipath);
string s = encoding.GetString(Buffer);
s = s.Substring(0, bufLen);
return s.Trim();
}
catch (Exception)
{
return "";
}
}
public string IniReadValue(string Section, string Key)
{
try
{
StringBuilder temp = new StringBuilder(500);
int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath);
return temp.ToString();
}
catch (Exception)
{
return "";
}
}
}
调用:
IniConfig ic = new IniConfig();
if (!ic.CanRead())
{ic.IniWriteValue("DataBase", "Connect", "你好啊");}
//有中文时指定编码格式
ic.IniReadValue("DataBase", "Connect", Encoding.UTF8);
//没有中文直接调用
ic.IniReadValue("DataBase", "Connect");
原文地址:https://blog.csdn.net/fanwenhu/article/details/135860421
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!