Let's assume we write the program which interacts with 64-bit Windows OS. Here is the code which writes into HKEY_LOCAL_MACHINE registry of it.
- var softwareSubKey = Registry.LocalMachine.OpenSubKey
- ("Software", RegistryKeyPermissionCheck.ReadWriteSubTree);
- softwareSubKey.CreateSubKey("MySoftware");
Depending on whether our program was compiled at x86 or x64 platform we receive (maybe somewhat unexpectedly) different results. The reason for that is registry redirection feature which isolates 32-bit applications inside the
\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node path.
Registry redirection consistently works with the same location, so code below works consistently regardless of platform chosen (although operates with different physical path)
- private static void Write()
- {
- var softwareSubKey = Registry.LocalMachine.OpenSubKey
- ("Software", RegistryKeyPermissionCheck.ReadWriteSubTree);
- softwareSubKey.CreateSubKey("MySoftware");
- }
-
- private static void Delete()
- {
- var softwareSubKey = Registry.LocalMachine.OpenSubKey
- ("Software", RegistryKeyPermissionCheck.ReadWriteSubTree);
- try
- {
- softwareSubKey.DeleteSubKeyTree("MySoftware", true);
- }
- catch (ArgumentException)
- {
- Console.WriteLine("Gotcha!");
- Console.ReadKey();
- }
- }
-
- static void Main(string[] args)
- {
- Write();
- Delete();
- }
As you might have understood up to this point, if you rely on manually created registry entry at
\HKEY_LOCAL_MACHINE\SOFTWARE\MySoftware with your 32-bit application, ArgumentException will be fired.
All entries for which registry redirection is applied are described in the
documentation.
To override registry redirection use RegistryKey.OpenBaseKey overload which accepts RegistryView as a parameter. Check the code below
- var localMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
- var softwareSubKey = localMachine.OpenSubKey("Software", RegistryKeyPermissionCheck.ReadWriteSubTree);
- softwareSubKey.CreateSubKey("MySoftware");