Bogdan Doicin
Bogdan Doicin

Reputation: 2416

How Can I Correctly Use Registry Permissions to Delete a Registry Subkey in C#?

In the Windows Registry I have the subkey \HKEY_CURRENT_USER\HTMPTK, which has two values: Secret Token and Token. I want to delete the two values.

I attempted to use key.DeleteValue("Secret Token") (key is a RegistryKey variable), but I got an UnauthorizedAccessException, with the message Cannot write to the registry key.

Tinkering around MSDN and Google, to allow the program the access it needs, I found the RegistryPermission class, along with some examples as guidance. Thus, I wrote the following code:

private bool DeleteTokensFromRegistryEngine()
        {
            RegistryPermission perm = new RegistryPermission(PermissionState.Unrestricted);
            perm.AddPathList(RegistryPermissionAccess.AllAccess, "HKEY_CURRENT_USER\\HTMPTK");
            RegistryKey key = Registry.CurrentUser.OpenSubKey("HTMPTK");
            try
            {
                if (key != null)
                {
                    key.DeleteValue("Secret Token"); //the same error message here
                    key.DeleteValue("Token");
                }
            }
            catch (UnauthorizedAccessException U)
            {
                MessageBox.Show(U.Message);
                return false;
            }
            finally
            {
                key.Close();
            }
            return true;
        }

The problem did not disappear.

What am I doing wrong? How can I solve this problem?

Later edit:

  1. I double checked to see if I run the program as an Administrator. I do;
  2. Nothing suspicious signaled by Windows Defender;
  3. If it helps, I can delete the values from Registry Editor;

Upvotes: 1

Views: 924

Answers (1)

Bogdan Doicin
Bogdan Doicin

Reputation: 2416

The reason was because I was using the wrong OpenSubKey ctor. The correct one was:

OpenSubKey(String, RegistryRights)

In my case, the subkey should have been opened with:

RegistryKey key = Registry.CurrentUser.OpenSubKey("HTMPTK",RegistryKeyPermissionCheck.ReadWriteSubtree);

However, there is a better way: because I want to delete both values, it's easier if to delete the whole subkey. I applied this method, and the resulting code was:

        try
        {
            Registry.CurrentUser.DeleteSubKeyTree("HTMPTK", true);                
        }
        catch (UnauthorizedAccessException U)
        {
            MessageBox.Show(U.Message);
            return false;
        }

Upvotes: 1

Related Questions