Search code examples
c#registryuac

Unable to read registry: System.Security.SecurityException, Requested registry access is not allowed


I'm getting reported errors from users who are receiving the error "System.Security.SecurityException, Requested registry access is not allowed." when trying to read the registry. I can't think why someone would not have permission to read the registry and I'm unable to reproduce the problem on my Windows 7 PC. Affected users are running .NET 4.0

Here's the C# code I'm using:

var baseReg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
var key = baseReg.OpenSubKey(RegKey, RegistryKeyPermissionCheck.ReadSubTree);

if (key != null)
{
    var value = key.GetValue("DisableAutoUpdate", 0);
    if (value != null)
    {
        updatesDisabled = Convert.ToBoolean(value);
    }
}

EDIT: I've checked permissions on the registry key concerned for the affected user and standard Users have read permission for that key.

EDIT 2 and SOLUTION: According to the affected user, installing .NET 4.5.2 resolves the problem! I'm not sure why.

Thanks to @nozzleman's answer below this is fixed by forcing it to open the key as read-only. However it's odd that .NET 4.0 as 4.5.2 appear to behave differently.


Solution

  • There is an overload of the OpenSubKey(..)-Method that allows to add a third parameter. You could try passing RegistryRights.ReadKey with that one and see if that solves the issue.

    baseReg.OpenSubKey(
        RegKey, 
        RegistryKeyPermissionCheck.ReadSubTree
        RegistryRights.ReadKey);
    

    Alternatively, try the other overload accepting 2 parameters like so

    baseReg.OpenSubKey(RegKey, false); 
    

    This leads to opening the subkey readonly, and you dont neet to read the whole sub tree in the given szenario..