Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registry.LocalMachine.OpenSubKey() returns null

Tags:

c#

registry

I get a null back from this attempt to access the Windows Registry:

using (RegistryKey registry = Registry.LocalMachine.OpenSubKey(keyPath))

keyPath is SOFTWARE\\TestKey

The key is in the registry, so why is it not finding it under the Local Machine hive?

like image 252
PositiveGuy Avatar asked Aug 12 '09 21:08

PositiveGuy


3 Answers

It can happen if you are on a 64-bit machine. Create a helper class first (requires .NET 4.0 or later):

public class RegistryHelpers
{

    public static RegistryKey GetRegistryKey()
    {
        return GetRegistryKey(null);
    }

    public static RegistryKey GetRegistryKey(string keyPath)
    {
        RegistryKey localMachineRegistry
            = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
                                      Environment.Is64BitOperatingSystem
                                          ? RegistryView.Registry64
                                          : RegistryView.Registry32);

        return string.IsNullOrEmpty(keyPath)
            ? localMachineRegistry
            : localMachineRegistry.OpenSubKey(keyPath);
    }

    public static object GetRegistryValue(string keyPath, string keyName)
    {
        RegistryKey registry = GetRegistryKey(keyPath);
        return registry.GetValue(keyName);
    }
}

Usage:

string keyPath = @"SOFTWARE\MyApp\Settings";
string keyName = "MyAppConnectionStringKey";

object connectionString = RegistryHelpers.GetRegistryValue(keyPath, keyName);

Console.WriteLine(connectionString);
Console.ReadLine();
like image 139
Raghav Avatar answered Oct 17 '22 10:10

Raghav


In your comment to Dana you said you gave the ASP.NET account access. However, did you verify that that is the account that the site in running under? Impersonate and the anonymous access user can be easy to overlook.

UNTESTED CODE:

Response.Clear();  
Response.Write(Environment.UserDomainName + "\\" + Environment.UserName);  
Response.End();
like image 33
KellCOMnet Avatar answered Oct 17 '22 10:10

KellCOMnet


Just needed to change it from

using (RegistryKey registry = Registry.LocalMachine.OpenSubKey(keyPath))

to

using (RegistryKey registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default).OpenSubKey(keyPath))

(Use RegistryKey instead of Registry , add the RegistryView, and put the hive-Local Machine as a method parameter.)

like image 1
vapcguy Avatar answered Oct 17 '22 11:10

vapcguy