I tried to write a registry subkey and its corresponding value to registry like this:
const string subKey = @"SOFTWARE\Apple\Banana\";
const string regKey = "pip";
var rk = Registry.LocalMachine.OpenSubKey(subKey);
if (rk == null)
rk = Registry.LocalMachine.CreateSubKey(subKey);
var rv = rk.GetValue(regKey);
if (rv == null)
rk.SetValue(regKey, "XXX");
return rv.ToString();
Now the problem is that I when I look in the location manually (via regedit) I cannot see the folder SOFTWARE\Apple\Banana
in HKLM
.
But when I run the above code again and debug, I can see that both Registry.LocalMachine.OpenSubKey(subKey)
and rk.GetValue(regKey)
yields the before saved values. Yet I do not see the values in the given location via regedit. So on searching the registry, I can see the above keys and values in following locations:
HKEY_CURRENT_USER\Software\Classes\VirtualStore\MACHINE\SOFTWARE\Apple\Banana
HKEY_USERS\S-1-5-21-44266131-1313801407-2392705078-1000\Software\Classes\VirtualStore\MACHINE\SOFTWARE\Apple\Banana
Under both which the values remain exactly as I saved. So I realise this is from where my app reads the value though in my code I call it from HKLM\SOFTWARE\Apple\Banana\
..
Why is this happening? Is it related to access rights issue?
Is this expected behaviour? In the sense, this value is very important to me, so I am just knowing if there is some risk associated with auto-relocation!
Is there a proper way of writing to registry so that it remains in its exact location..
My account is administrator one, and I am using 32 bit windows 7.
Edit: As I came to know, the registry entry is stored in current users location rather than HKLM. And when I query for the reg value from a different account, I do not get the value. In short, no point in first of all saving it to HKLM :(
This is Registry Virtualization (msdn)
Yes it is exactly as it should be.
Either live with Virtualization if you want to write to globally impacting location, or use more localised locations if you don't want it. Either way it's invisible to the reader, so don't worry about it.
Yes this is correct behaviour and it is happening because you have insufficient privileges to write directly to the HKLM hive. It's called virtualisation and happens for the file system as well, it has been a behaviour in the OS since Vista.
You should continue as you are and attempt to also read from the same HKLM key you are writing to, Windows will transparently redirect for you.
Preet has kindly provided a MSDN link which you should read thoroughly.
Note that when you access a key under HKLM you should also include the permissions you want, even if you are running as administrator (because the key is not automatically opened with admin rights, you have to request it):