Overriding Windows Registry Redirection With C#

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. 
  1. var softwareSubKey = Registry.LocalMachine.OpenSubKey  
  2.                      ("Software", RegistryKeyPermissionCheck.ReadWriteSubTree);  
  3. 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) 
  1. private static void Write()  
  2. {  
  3.     var softwareSubKey = Registry.LocalMachine.OpenSubKey  
  4.                          ("Software", RegistryKeyPermissionCheck.ReadWriteSubTree);  
  5.     softwareSubKey.CreateSubKey("MySoftware");             
  6. }  
  7.   
  8. private static void Delete()  
  9. {  
  10.     var softwareSubKey = Registry.LocalMachine.OpenSubKey  
  11.                          ("Software", RegistryKeyPermissionCheck.ReadWriteSubTree);  
  12.     try  
  13.     {  
  14.         softwareSubKey.DeleteSubKeyTree("MySoftware"true);  
  15.     }  
  16.     catch (ArgumentException)  
  17.     {  
  18.         Console.WriteLine("Gotcha!");  
  19.         Console.ReadKey();  
  20.     }             
  21. }  
  22.   
  23. static void Main(string[] args)  
  24. {  
  25.     Write();  
  26.     Delete();  
  27. }  
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  
  1. var localMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);  
  2. var softwareSubKey = localMachine.OpenSubKey("Software", RegistryKeyPermissionCheck.ReadWriteSubTree);  
  3. softwareSubKey.CreateSubKey("MySoftware");  
Next Recommended Reading Override ToString() Method in C#