Finding Registry Keys in C# - c#

I am working on a project that will allow me to delete the registry key from a Windows 7 PC. Specifically I am trying to make a program that will allow me to delete a profile from the machine via the ProfileList key. My problem is no matter what I try I can't seem to read the key correctly which I want to do before I start randomly deleting stuff. My code is
RegistryKey OurKey = Registry.LocalMachine;
OurKey = OurKey.OpenSubKey(#"SOFTWARE\Microsoft\WindowsNT\CurrentVersion\ProfileList", true);
foreach (string Keyname in OurKey.GetSubKeyNames())
{
MessageBox.Show(Keyname);
}
This code runs but doesn't return anything (No MessageBox). Any ideas why not?
EDIT:
I got the top level keys to load thanks to you all but it does only show the folder/key names (Ex: S-1-5-21-3794573037-2687555854-1483818651-11661) what I need is to read the keys under that folder to see what the ProfilePath is. Would there be a better way to go about that?

As pointed out by Lloyd, your path should use "Windows NT". In case of doubt, always use regedit to go inspect the registry manually.
Edit: To go with your edit, you can simply GetValue on the keys you find, the following code should do what you're looking for:
RegistryKey OurKey = Registry.LocalMachine;
OurKey = OurKey.OpenSubKey(#"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList", true);
foreach (string Keyname in OurKey.GetSubKeyNames())
{
RegistryKey key = OurKey.OpenSubKey(Keyname);
MessageBox.Show(key.GetValue("KEY_NAME").ToString()); // Replace KEY_NAME with what you're looking for
}

Windows NT
Please do not miss space

Related

How to export a registry key in C#

I am trying to write a C# code, which will block exe files from running. I found a question about the same topic: example question. In the question suggested method is using these registry lines as below:
REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe]
"Debugger"="calc.exe"
However, this code doesn't look like any C# code I have ever seen. The answer talks about "adding a registry key" and "exported registry key". However, when I search those terminologies on the internet, I could not find any clear explanation about the topic for a beginner Windows developer like me.
For example this question add registry key question wrote a C# function with two inputs.
void exportRegistry(string strKey, string filepath)
I tried to use this function inside my main Winform constructor as below, but nothing happened - I could still open notepad.exe with no problem (which is the main aim of the code)
this.exportRegistry("\"Debugger\" = \"calc.exe\"", "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\notepad.exe]");
What am I doing wrong? I really thought I have enough coding skill for this problem, but I am stuck.
After I searched for some time, I found a way to achieve it. I can know stop programs running by changing the registery for windows. This code stops notepad.exe from running. It does it by adding several registery keys with the C# code. The logic behind it given in this link Explanation. It might not be the best way but it does stop programs running.
RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
key.CreateSubKey("Microsoft");
key = key.OpenSubKey("Microsoft", true);
key.CreateSubKey("Windows");
key = key.OpenSubKey("Windows", true);
key.CreateSubKey("CurrentVersion");
key = key.OpenSubKey("CurrentVersion", true);
key.CreateSubKey("Policies");
key = key.OpenSubKey("Policies", true);
RegistryKey explorerKey = key.CreateSubKey("explorer");
key = key.OpenSubKey("explorer", true);
explorerKey.SetValue("DisallowRun", 0x00000001, RegistryValueKind.DWord);
RegistryKey disallowRun = key.CreateSubKey("DisallowRun");
key = key.OpenSubKey("DisallowRun", true);
disallowRun.SetValue("1", "notepad.exe", RegistryValueKind.String);

Accessing all the keys under classesroot from registry with c#

I have a program which i try is to read all the keys under classesroot but when i do it with GetSubKeyNames() many keys are skipped i only get the key which contains another sub key on it.
RegistryKey key = Registry.ClassesRoot;
foreach (string tempKeyName in key.GetSubKeyNames())
{
MessageBox.Show(tempKeyName);
}
enter image description here
This code shows all the registry keys under HKEY_CLASSES_ROOT. If it doesn't work for you, edit your question telling us Windows version and maybe if you are under a corporate network.
RegistryKey rk = Registry.ClassesRoot;
// Print out the keys.
PrintKeys(rk);
PrintKeys:
static void PrintKeys(RegistryKey rkey)
{
// Retrieve all the subkeys for the specified key.
String[] names = rkey.GetSubKeyNames();
Console.WriteLine("Subkeys of " + rkey.Name);
Console.WriteLine("-----------------------------------------------");
// Print the contents of the array to the console.
foreach (String s in names)
{
Console.WriteLine(s);
}
}
Source:MSDN
JANUARY 2022 - This issue is due to breaking changes introduced in the framework's registry searching library that apparently are not well known
For those searching and still coming up with incorrect registry key results this is due to the 32/64 redirecting in place by Microsoft. This means the old route of iterating for a key in the ClassesRoot hive using Registry.ClassesRoot could unknowingly search the Wow6432 key instead.
The new route is to look it up using the base key while explicitly defining where it should search. Here's the current way to correctly search for a key if you are having this trouble:
RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry64)
Note the use of the RegistryKey static member instead of Registry
You can explicitly tell it to look in Registry32, Registry64, or Default - the later of which is what the old process of Registry.ClassesRoot appears to follow.

Using OpenSubKey not finding node that exists

I am using the cookie cutter code to get a registry key object in C#:
RegistryKey reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\MyNewKeyName\\");
After I run this code reg = null. However, if I switch the value passed to OpenSubKey to be any value in the registry under SOFTWARE that has additional nodes below it reg will now have a value. I've tried multiple keys with this pattern and it works. If I put any any key name that does not have additional child nodes it does not work. Ultimately I'm trying to read a string value inside of MyNewKeyName.
Why does my code not work and reg get populated if my key does not have any additional nodes below it?
Well it turns out that the values in the '32-bit' registry and the '64-bit' registry are not identical. So when viewing the registry via 'regedit' and seeing everything, programatically you may not and that's the issue I was running into. I noticed this by running GetSubKeyNames() and inspecting the keys returned. The quick answer is to check both versions of the registry to find the value sought:
//Check the 64-bit registry for "HKEY_LOCAL_MACHINE\SOFTWARE" 1st:
RegistryKey localMachineRegistry64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey reg64 = localMachineRegistry64.OpenSubKey(registryKeyLocation, false);
if (reg64 != null)
{
return reg64.GetValue(registryKeyName, true).ToString();
}
//Check the 32-bit registry for "HKEY_LOCAL_MACHINE\SOFTWARE" if not found in the 64-bit registry:
RegistryKey localMachineRegistry32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
RegistryKey reg32 = localMachineRegistry32.OpenSubKey(registryKeyLocation, false);
if (reg32 != null)
{
return reg32.GetValue(registryKeyName, true).ToString();
}
I think the problem is you are compiling it as x86 instead of compiling it as an x64 application. Follow the below steps:
Right click on Project
Select Properties
Select the Build tab
Change "Platform Target" to "x64"
Now run the project.

Writing to registry in a C# application

I'm trying to write to the registry using my C# app.
I'm using the answer given here: Writing values to the registry with C#
However for some reason the key isn't added to the registry.
I'm using the following code:
string Timestamp = DateTime.Now.ToString("dd-MM-yyyy");
string key = "HKEY_LOCAL_MACHINE\\SOFTWARE\\"+Application.ProductName+"\\"+Application.ProductVersion;
string valueName = "Trial Period";
Microsoft.Win32.Registry.SetValue(key, valueName, Timestamp, Microsoft.Win32.RegistryValueKind.String);
The Application.name and Application.version 'folders' don't exists yet.
Do I have to create them first?
Also, I'm testing it on a 64b Win version so I think if I want to check the registry for the key added I have to specifically check the 32bit registry in: C:\Windows\SysWOW64\regedit.exe don't I?
First of all if you want to edit key under LocalMachine you must run your application under admin rights (better use CurrentUser it's safer or create the key in installer). You have to open key in edit mode too (OpenSubKey method) to add new subkeys. I've checked the code and it works. Here is the code.
RegistryKey key = Registry.LocalMachine.OpenSubKey("Software",true);
key.CreateSubKey("AppName");
key = key.OpenSubKey("AppName", true);
key.CreateSubKey("AppVersion");
key = key.OpenSubKey("AppVersion", true);
key.SetValue("yourkey", "yourvalue");
You can use the following code to create and open the required registry keys.
RegistryKey SoftwareKey = Registry.LocalMachine.OpenSubKey("Software",true);
RegistryKey AppNameKey = SoftwareKey.CreateSubKey("AppName");
RegistryKey AppVersionKey = AppNameKey.CreateSubKey("AppVersion");
AppVersionKey.SetValue("yourkey", "yourvalue");
You can basically use CreateSubKey for all your application settings, as it will open the key for write access, if it already exists, and create it otherwise. There is no need to create first, and then open. OpenSubKey comes in handy when you are absolutely certain the key already exists, like in this case, with "HKEY_LOCAL_MACHINE\SOFTWARE\"
Also check if your registry calls are getting virtualised. See here for more information.
It can happen if your application is not UAC aware and occurs for compatibility reasons.
Real path
HKEY_LOCAL_MACHINE\Software\FooKey
Virtual path
HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\Software\FooKey
Try to open HKLM\Software first. Then create key for your program, and then create key for version. Howewer, your key could be placed at HKLM\software\WOW6432Node. Check this.
The problem is you don't have enough privileges. Here is a way that works for my:
RegistryKey myKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
myKey = myKey.OpenSubKey(subkey, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
if (myKey != null)
{
myKey.SetValue("DefaultPrinterId", ldiPrinters[e.RowIndex].id, RegistryValueKind.String);
myKey.Close();
}
With RegistryKey.OpenBaseKey you open the correct registry, because when you don't have permissions the registry that you write, it does in another location.
By default, your changes will be written to HKLM\SOFTWARE\WOW6432Node\... because of registry redirection. This can be quite confusing.
In order to write to HKLM\SOFTWARE\..., you need to use RegistryKey.OpenBaseKey to open the 64-bit registry:
var path = #"SOFTWARE\...";
var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
var key = baseKey.CreateSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree);
key.SetValue(name, value, RegistryValueKind.String);
Also, you need to have permission to write to the specified registry key.
You can get permission either by assigning permissions to specific users or service accounts or by running your app in elevated mode.

Get value of registry key C#

I have already looked at existing topics, so please try to refrain from dropping links here.
I want to get the value of a registry key - plain and simple. Here is what I have so far.
Registry:
1) Made a key under
Current_User\Software\Custom_Subkey\Custom_Value\Custom_key\string_value
I am trying to find the string_value
string reg_subKey = "Software\\Custom_Subkey\\Custom_Value";
RegistryKey root = Registry.CurrentUser.CreateSubKey(reg_subKey);
foreach (string keyname in root.GetValueNames())
{
textBox4.AppendText(keyname.ToString() + Environment.NewLine);
// Appends the following data to textBox4 once the foreach is completed:
// Header1
// Header2
// Header3
// Header4
// Header5
// Now I want to get the VALUES of each header:
using (RegistryKey key = root.OpenSubKey(keyname))
{
**// THIS LINE GETS HIGHLIGHTED WITH THE FOLLOWING ERROR:
"Object reference not set to an instance of an object.**"
MessageBox.Show(key.ValueCount.ToString());
}
}
Hopefully this is a simple fix. I look forward to hearing your responses.
Thanks,
Evan
I believe you want root.GetSubKeyNames() in the loop not GetValueNames()
While values is working to get the values I would suggest the following loop:
foreach(string keyname in root.GetSubKeyNames())
{
// use key to get value and set textbox4
using (RegistryKey key = root.OpenSubKey(keyname))
{
MessageBox.Show(key.ValueCount.ToString());
}
}
The OpenSubKey method does not throw an exception if the specified subkey is not found. Instead, it simply returns null. It's your responsibility as a programmer to ensure that the appropriate key was found and opened by checking the return value of the method call.
Thus, my suspicion is that the registry key that you've specified is invalid. Open up Registry Editor (regedt32.exe), and verify that you can find the key in the registry exactly as written.
If you find that the registry key is indeed located exactly where you thought it was, then the problem may be related to the WOW64 subsystem, which allows 64-bit versions of Windows to run 64-bit apps. If the value was written to the registry by a 32-bit program, you won't be able to read it with the above code from a 64-bit program (or vice versa). The simplest way to check this is to change the compilation settings for your project. For example, if you're currently compiling for x86, then change to compiling for x64, or vice versa. Registry redirection may also be getting in your way; this will check for that as well.
I wanted the very same thing and your code helped me, but as you said, it didn't work properly. So, I made some modifications and I think it works fine now! Try this:
//Just make the reference until "custom_subkey", not to the next one ("custom value")
string reg_subKey = "Software\\Custom_Subkey";
RegistryKey root = Registry.CurrentUser.CreateSubKey(reg_subKey);
//Use GetSubKeyNames, instead of GetValueNames, because now you are in a higher level
foreach (string keyname in root.GetSubKeyNames())
{
using (RegistryKey key = root.OpenSubKey(keyname))
{
foreach (string valueName in key.GetValueNames())
{
MessageBox.Show(valueName);
MessageBox.Show(key.GetValue(valueName).ToString() );
}
}
}

Categories

Resources