user3308131
user3308131

Reputation: 179

Can't Read Registry Key

give the code below, lastuser string returns null, however, if I use regedit to look at this key it has data associated with it. Is LoggedOnSAMuser a restricted key?

public static string lastlogon()
    {
        string lastuser;
        RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
        RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI",false);
        if (registryKey != null)
        {
            lastuser = (string) registryKey.GetValue("LastLoggedOnSAMUser");
        }
        else lastuser = "Unknown User";
        return (lastuser);
    }

Upvotes: 2

Views: 5995

Answers (3)

Billy Willoughby
Billy Willoughby

Reputation: 856

This seems to work on Windows 7

    RegistryKey thisKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
    RegistryKey thisSubkey = thisKey.OpenSubKey(@"SOFTWARE\\fred", false);
    _url = (string)thisSubkey.GetValue("_url", "*");
    _port = (string)thisSubkey.GetValue("_port", 0);

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613491

Almost certainly you have a 32 bit process on a 64 bit machine and so are subject to registry redirection. Your 32 bit process, by default, reads from the 32 bit view of the registry. But you want to read from the 64 bit view.

Solve the problem by requesting that you read from the 64 bit view of the registry, by way of the RegistryView enumeration.

Upvotes: 0

decPL
decPL

Reputation: 5402

2 possible issues:

  1. You are trying to read the LoggedOnSAMUser key, quite a chance you meant LastLoggedOnSAMUser.
  2. You might be trying to read a 64-bit registry entry from a 32-bit application. If possible, change your platform target to x64 and retry. If not possible, you might have to use the registry API directly. Hopefully a nudge in the right directon: link

Upvotes: 7

Related Questions