C# Registry SetValue throws UnauthorizedAccessException

Middas picture Middas · Aug 1, 2012 · Viewed 17.8k times · Source

Before you try to answer this with, "Do a quick Google search." I'd like to point out that I have already. Here is the situation, I have the following method that attempts to modify a registry key value. The problem I'm getting is that when executed, it throws an UnauthorizedAccessException even though I've opened the key as writeable. I'm running Visual Studio as administrator and even tried to make a small .exe with a manifest file forcing it to run as admin that will execute the code with no luck. The key already exists, it doesn't try to go into the CreateKey method. Here is the block of code.

Path = "S-1-5-21-1644491937-1078145449-682003330-5490\Software\Microsoft\Windows\CurrentVersion\Policies\System"
Key = "DisableTaskMgr"
NewValue = 1

public OperationResult ModifyKey()
    {
        OperationResult result = new OperationResult();

        if (!Path.IsNullOrEmptyTrim())
        {
            if (!Key.IsNullOrEmptyTrim())
            {
                try
                {
                    var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, true);

                    if (key != null)
                    {
                        key.SetValue(Key, NewValue);

                        key.Close();
                    }
                    else
                    {
                        result = CreateKey();
                    }
                }
                catch (Exception ex)
                {
                    result.SetFail("Error accessing registry", ex);
                }
            }
            else
            {
                result.SetFail("Registry key was null");
            }
        }
        else
        {
            result.SetFail("Registry path was null");
        }

        return result;
    }

Do I have to manually walk down the registry tree setting each OpenSubKey call to writeable? I tried this as well, still threw the same error...

Answer

Sorceri picture Sorceri · Aug 2, 2012

in the var for your key

var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, true);

change to

var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, RegistryKeyPermissionCheck.ReadWriteSubTree);