Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegistryKey.OpenSubKey throws SecurityException

Tags:

c#

registry

There are possible duplicates to this question here and here, but they have never been answered sufficiently.

I had the pleasure of renaming a Users folder and had to change "a few" keys in the registry. This is done, but I am curious if one can automate this process. For this purpose I tried to traverse the registry tree like this:

using Microsoft.Win32;
using System;
using System.Collections.Generic;

namespace RegistryReplacer
{
    class Program
    {

        private static void printKey(RegistryKey key)
        {
                Console.WriteLine("{0} has {1} sub keys", key.Name, key.SubKeyCount);
        }

        private static void traverseKey(RegistryKey key)
        {
            using (key)
            {
                printKey(key);

                string[] subKeyNames = key.GetSubKeyNames();
                foreach(string subKeyName in subKeyNames)
                {
                    RegistryKey subKey = key.OpenSubKey(subKeyName);
                    traverseKey(subKey);
                }

            }
        }


        static void Main(string[] args)
        {
            List<RegistryKey> rootKeys = new List<RegistryKey> {
                Registry.LocalMachine,
                Registry.CurrentUser,
                Registry.ClassesRoot,
                Registry.CurrentConfig,
                Registry.Users
            };

            foreach (RegistryKey rootKey in rootKeys)
            {
                traverseKey(rootKey);
            }
        }
    }
}

I can traverse the roots of the tree (LocalMachine etc.), but when calling OpenSubKey on some keys (not all), I encounter

System.Security.SecurityException: 'Requested registry access is not allowed.'

I am running the application with administrator rights (using rightclick+"Run as administrator" or using this), but this does not help. This is on my personal machine (64bit Windows 10 Pro, Version 2004), I am administrator and have sufficient rights to change the registry via regedit.

What am I doing wrong?

like image 866
Jerome Reinländer Avatar asked Jul 12 '26 18:07

Jerome Reinländer


1 Answers

The issue is related to the registry key ownership - it is very likely has custom permissions and owned by SYSTEM, TrustedInstaller or some other account.

Here is a very good answer which explains issue in depth: https://superuser.com/a/493121.

So, you are doing everything correctly and it does not work as expected. "This is not a bug, this is a feature" (c)

like image 168
fenixil Avatar answered Jul 14 '26 08:07

fenixil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!