我正在使用以下代码从注册表中读取值。该值由C++应用程序写入注册表。我面临的问题是,从C#应用程序读取的值具有一些终止垃圾字符。如果我手动将字符串写入注册表,则在C#中读取的值是正确的。从注册表中读取字符串值会产生一些垃圾字符
string strPath = "SOFTWARE\\SUKHAS\\TEST\\";
string strName = "ActiveLayoutName";
try
{
using (RegistryKey regKeyExt = Registry.CurrentUser.OpenSubKey(strPath))
{
if (regKeyExt != null)
{
string strLayoutName = "";
object obj = regKeyExt.GetValue(strName, strLayoutName);
LayoutName = obj as string;
}
}
}
catch (Exception ex)
{
}
将值写入注册表的主要C++代码。
DWORD len = (DWORD)((_tcslen(lNewValue) * sizeof(TCHAR)) + 1);
//Does this cause problem? +1? if I remove the +1, I am not getting the junk character in C# application.
result = RegSetValueEx(hResultKey, lpRegSzName, 0, REG_SZ, (LPBYTE)lNewValue, len);
RegCloseKey(hResultKey);
任何线索?这是因为这个问题导致问题的长度为+1
?
作为每函数RegSetValueEx的文档,
的信息的大小所指向的lpData参数,以字节为单位。如果数据类型为REG_SZ,REG_EXPAND_SZ或REG_MULTI_SZ,则cbData必须包含终止空字符的大小。
我不确定是什么导致了问题。
什么是TCHAR,char或wchar_t? – Niall
你想'(_tcslen(lNewValue)+ 1)* sizeof(TCHAR)'。 – molbdnilo
为什么我会在c#应用程序中看到垃圾字符? – Sukhas