C# 利用windowsAPI如何读取unicode形式保存的ini文件?
1. ini文件内容都是英文;
2. 写字板编辑文件,保存时选Unicode;
3. 读取时用的是API的GetPrivateProfileStringA方法,然后用Unicode转换成字符串,相关代码如下:
--------------------------------------------------
[DllImport("KERNEL32.DLL",
EntryPoint = "GetPrivateProfileStringA")]
private static extern uint
GetPrivateProfileStringByByteArray(string lpAppName,
string lpKeyName, string lpDefault,
byte[] lpReturnedString, uint nSize,
string lpFileName);
--------------------------------------------------
string iniUNfile = "../my.ini";
byte[] byteAr = new byte[1024];
UInt resultSize = GetPrivateProfileStringByByteArray(section, name, defaultMsg + section + "." + name,byteAr, (UInt32)byteAr.Length, iniUNfile);
string strall = Encoding.Unicode.GetString(byteAr, 0, (int)resultSize);
--------------------------------------------------
section和键值都能正常辨认,但读出来的是乱码。
如果换成UTF8的话(文件用UTF8保存,转换也用UTF8),一切正常,可惜项目要求用Unicode。
看起来很简单的问题,请各位大虾指点。
------解决方案--------------------
EntryPoint = "GetPrivateProfileStringA"
改成
EntryPoint = "GetPrivateProfileStringW"
------解决方案--------------------
C# code
[DllImport("KERNEL32.DLL", EntryPoint = "GetPrivateProfileStringW", CharSet = CharSet.Unicode)]
private static extern uint GetPrivateProfileStringByByteArray(string lpAppName, string lpKeyName, string lpDefault, byte[] lpReturnedString, uint nSize, string lpFileName);
string iniUNfile = "../my.ini";
byte[] byteAr = new byte[1024];
uint resultSize = GetPrivateProfileStringByByteArray(section, name, defaultMsg + section + "." + name, byteAr, (uint)byteAr.Length, iniUNfile);
string strall = Encoding.Unicode.GetString(byteAr, 0, (int)resultSize * 2);