问题
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);
}
回答1:
2 possible issues:
- You are trying to read the
LoggedOnSAMUser
key, quite a chance you meantLastLoggedOnSAMUser
. - 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
回答2:
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.
回答3:
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);
来源:https://stackoverflow.com/questions/26299421/cant-read-registry-key