I need to query the registry through keywords and return all matching registry addresses, but I cannot access the following branches with this function。
HKEY_LOCAL_MACHINE\SOFTWARE\abc\test
HKEY_LOCAL_MACHINE\SYSTEM\test
WHY? I don't know where to write the question。 Thanks.
keywork="test"
I am in VS, have used administrator rights.
public static DataTable SearchRegistry(string keyword)
{
// List<string> matchedAddresses = new List<string>();
DataTable dataTable = new DataTable("MyTable");
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("HOST", typeof(string));
try
{
SearchRegistryKeys(Registry.ClassesRoot, keyword, "", dataTable);
SearchRegistryKeys(Registry.CurrentUser, keyword, "", dataTable);
SearchRegistryKeys(Registry.LocalMachine, keyword, "", dataTable);
SearchRegistryKeys(Registry.Users, keyword, "", dataTable);
SearchRegistryKeys(Registry.CurrentConfig, keyword, "", dataTable);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return dataTable;
}
public static void SearchRegistryKeys(RegistryKey key, string keyword, string currentPath, DataTable dataTable)
{
string registername = key.Name;
foreach (string subKeyName in key.GetSubKeyNames())
{
using (RegistryKey subKey = key.OpenSubKey(subKeyName))
{
if (subKey != null)
{
if (subKeyName.ToLower().Contains(keyword) )
{
// dataTable.Rows.Add(subKeyName);
dataTable.Rows.Add($"{currentPath}\\{subKeyName}", "");
}
SearchRegistryKeys(subKey, keyword, $"{currentPath}\\{subKeyName}", dataTable);
}
}
}
}
【erro msg】:The requested registry access is not allowed
There were two issues in you code. One is that some registry is unaccessible even if with admin right. The other is that GetSubKeyNames might return null. The following code should work. Please make sure that your project is x64 or "Any CPU" (With "Prefer 32-bit" unchecked) architecture. If the project is x86, "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node" will be searched instead of "HKEY_LOCAL_MACHINE\SOFTWARE".
public static void SearchRegistryKeys(RegistryKey key, string keyword, string currentPath, DataTable dataTable)
{
try
{
string registername = key.Name;
//GetSubKeyNames might return null
var subKeyNames = key.GetSubKeyNames();
if (subKeyNames == null)
{
return;
}
foreach (string subKeyName in subKeyNames)
{
try
{
using (RegistryKey subKey = key.OpenSubKey(subKeyName))
{
if (subKey != null)
{
if (subKeyName.ToLower().Contains(keyword))
{
dataTable.Rows.Add($"{currentPath}\\{subKeyName}", "");
}
SearchRegistryKeys(subKey, keyword, $"{currentPath}\\{subKeyName}", dataTable);
}
}
}
catch (SecurityException)
{
//Some registry is unaccessible
Console.WriteLine($"Cannot access {currentPath}\\{subKeyName}");
}
catch
{
throw;
}
}
}
catch (SecurityException)
{
//Some registry is unaccessible
Console.WriteLine($"Cannot access {currentPath}");
}
catch
{
throw;
}
}