Accessing 64-bit Registry Entries from a 32-bit .NET Application
Accessing the 64-bit registry from a 32-bit application running on a 64-bit Windows system requires a specific approach. Fortunately, the .NET Framework 4.x and later versions offer built-in support for this.
Leveraging RegistryView for 64-bit Registry Access
The RegistryView
enumeration is key to differentiating between 32-bit and 64-bit registry access. Here's how to use it:
<code class="language-csharp">// Access the 64-bit registry using Microsoft.Win32; RegistryKey localKey64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); RegistryKey sqlServerKey64 = localKey64.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"); // Access the 32-bit registry RegistryKey localKey32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); RegistryKey sqlServerKey32 = localKey32.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL");</code>
Retrieving Specific Registry Values
To retrieve a specific value, such as "SQLEXPRESS" under the "Instance NamesSQL" key, use:
<code class="language-csharp">string sqlExpressKeyName = (string)sqlServerKey64.GetValue("SQLEXPRESS");</code>
Comprehensive Key Retrieval: Combining 32-bit and 64-bit Results
For situations needing data from both 32-bit and 64-bit registry locations, a combined query is beneficial:
<code class="language-csharp">using System.Linq; IEnumerable<string> GetAllRegValueNames(string regPath) { var reg64 = GetRegValueNames(RegistryView.Registry64, regPath); var reg32 = GetRegValueNames(RegistryView.Registry32, regPath); var result = (reg64 != null && reg32 != null) ? reg64.Union(reg32) : (reg64 ?? reg32); return (result ?? new List<string>().AsEnumerable()).OrderBy(x => x); }</code>
Where GetRegValueNames
is a helper function (not shown, but easily implemented) that retrieves value names under a given key. regPath
specifies the registry path.
Example usage:
<code class="language-csharp"> var sqlRegPath = @"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"; foreach (var keyName in GetAllRegValueNames(sqlRegPath)) { Console.WriteLine(keyName); } ``` This iterates through all found keys, regardless of whether they reside in the 32-bit or 64-bit registry hive.</code>
The above is the detailed content of How to Access 64-bit Registry Keys from a 32-bit .NET Application?. For more information, please follow other related articles on the PHP Chinese website!