I want to delete an Registrykey, but on this code I get always the Returnvalue 2 (file not found), but the path equals the parameter.
HKEY hKey;
long lReturn = RegOpenKeyEx( HKEY_CURRENT_USER,
_T("test1\\test2\\test3"),
0L,
KEY_ALL_ACCESS,
&hKey );
lReturn = RegDeleteValue(hKey,(LPCWSTR)"value1");
lReturn = RegDeleteValue(hKey,(LPCWSTR)"value2");
lReturn = RegDeleteKey(hKey,(LPCWSTR)"test1\\test2\\test3");
lReturn = RegDeleteKey(hKey,(LPCWSTR)"test1\\test2");
lReturn = RegCloseKey(hKey);
If i change the RegDeleteKey parameter to:
lReturn = RegDeleteKey(HKEY_LOCAL_MACHINE,(LPCWSTR)"test1\\test2\\test3");
I get the Returnvalue 5(no access). Please help me to delete this Registryentry.
Type-casting a string literal to LPCWSTR does not convert it to that type. It just tells the compiler that despite the literal's real type, you know better and that it should be treated as the other type instead. The compiler doesn't check whether you're telling the truth, and in this case, you're wrong.
If you want a wide-character string literal, use the L
prefix, or else use the _T
macro like you did in the first statement:
lReturn = RegDeleteValue(hKey, L"value1");
lReturn = RegDeleteValue(hKey, _T("value1"));
The OS is correct to return 2 since the value you're pointing at really cannot be found as-is. With a type-cast to LPCWSTR, the function expects the pointer to point at a sequence of two-byte characters. You gave it a sequence of one-byte characters, though. It reads the first pair of bytes and treats it as a single character. It reads 'va'
or 'te'
as a single character, finds no values or keys with names starting with such a character, and fails.
When using the L
prefix, it's common to also explicitly use the W
version of an API function so that selection of the function won't be sensitive to the state of the UNICODE
macro.
lReturn = RegDeleteValueW(hKey, L"value1");