Reputation: 1257
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?
Upvotes: 4
Views: 1513
Reputation: 2124
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)
Upvotes: 1