Delete Registry Subkey C# [duplicate] - c#

I can get/set registry values using the Microsoft.Win32.Registry class. For example,
Microsoft.Win32.Registry.SetValue(
#"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run",
"MyApp",
Application.ExecutablePath);
But I can't delete any value. How do I delete a registry value?

To delete the value set in your question:
string keyName = #"Software\Microsoft\Windows\CurrentVersion\Run";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
if (key == null)
{
// Key doesn't exist. Do whatever you want to handle
// this case
}
else
{
key.DeleteValue("MyApp");
}
}
Look at the docs for Registry.CurrentUser, RegistryKey.OpenSubKey and RegistryKey.DeleteValue for more info.

To delete all subkeys/values in the tree (~recursively), here's an extension method that I use:
public static void DeleteSubKeyTree(this RegistryKey key, string subkey,
bool throwOnMissingSubKey)
{
if (!throwOnMissingSubKey && key.OpenSubKey(subkey) == null) { return; }
key.DeleteSubKeyTree(subkey);
}
Usage:
string keyName = #"Software\Microsoft\Windows\CurrentVersion\Run";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
key.DeleteSubKeyTree("MyApp",false);
}

RegistryKey registrykeyHKLM = Registry.LocalMachine;
string keyPath = #"Software\Microsoft\Windows\CurrentVersion\Run\MyApp";
registrykeyHKLM.DeleteValue(keyPath);
registrykeyHKLM.Close();

RegistryKey.DeleteValue

string explorerKeyPath = #"Software\TestKey";
using (RegistryKey explorerKey = Registry.CurrentUser.OpenSubKey(explorerKeyPath, writable: true))
{
if (explorerKey != null)
{
explorerKey.DeleteSubKeyTree("TestSubKey");
}
}

I Needed something a little different, I just needed to delete everything a key contained. Therefore the below
Registry.LocalMachine.DeleteSubKeyTree(#"SOFTWARE\YourNeededKeyThatHasMany\");
Note that here its using LocalMachine so it's looking in "HKEY_LOCAL_MACHINE" for the Key to delete its SubTreeKeys. Was simpler for me to do this and would've liked to see this simple answer here.

Related

search an uninstall from registry key C#

I want to uninstall some app programmatically. I'm searching in this path in win registry:
\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\
the code for searching and uninstalling is the following:
public string UninstallCMD;
public bool SearchApp(string p_name)
{
string displayName;
RegistryKey key;
key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
foreach (String keyName in key.GetSubKeyNames())
{
RegistryKey subkey = key.OpenSubKey(keyName);
displayName = subkey.GetValue("DisplayName") as string;
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
{
UninstallCMD = subkey.GetValue("UninstallString") as string;
return true;
}
}
}
My problem is that not all the key were read. The key that I want to be read is {56DDDFB8-7F79-4480-89D5-25E1F52AB28F} but is ignored like the other in { } (in this image you can see the key ignored)
The key without { } were read normally (i.e. 7-zip, VLC media player, ...)
I don't know why but after recompiling solution, everything work fine.

How do I change properties on control panel with visual studio [duplicate]

I'm trying to spoof the MAC address of the computer that executes my program. Right now I'm getting the current MAC address of the machine using the 'getmac' command via cmd, then I want to change it via the 'RegistryKey' class(windows.system32).
The issue is that I don't know the string to pass to the OpenSubKey method.
For example this is the method to read the current MAC with registry key reading:
private string readMAC()
{
RegistryKey rkey;
string MAC;
rkey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\0012", true); //--->this is the string to change
MAC = (string)rkey.GetValue("NetworkAddress");
rkey.Close();
return MAC;
}
I got curious so I pulled the source for MadMACs. Turned out to be pretty straightforward to port the core logic to C#, so here it is if anyone is interested.
private const string baseReg =
#"SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\";
public static bool SetMAC(string nicid, string newmac)
{
bool ret = false;
using (RegistryKey bkey = GetBaseKey())
using (RegistryKey key = bkey.OpenSubKey(baseReg + nicid))
{
if (key != null)
{
key.SetValue("NetworkAddress", newmac, RegistryValueKind.String);
ManagementObjectSearcher mos = new ManagementObjectSearcher(
new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE Index = " + nicid));
foreach (ManagementObject o in mos.Get().OfType<ManagementObject>())
{
o.InvokeMethod("Disable", null);
o.InvokeMethod("Enable", null);
ret = true;
}
}
}
return ret;
}
public static IEnumerable<string> GetNicIds()
{
using (RegistryKey bkey = GetBaseKey())
using (RegistryKey key = bkey.OpenSubKey(baseReg))
{
if (key != null)
{
foreach (string name in key.GetSubKeyNames().Where(n => n != "Properties"))
{
using (RegistryKey sub = key.OpenSubKey(name))
{
if (sub != null)
{
object busType = sub.GetValue("BusType");
string busStr = busType != null ? busType.ToString() : string.Empty;
if (busStr != string.Empty)
{
yield return name;
}
}
}
}
}
}
}
public static RegistryKey GetBaseKey()
{
return RegistryKey.OpenBaseKey(
RegistryHive.LocalMachine,
InternalCheckIsWow64() ? RegistryView.Registry64 : RegistryView.Registry32);
}
For brevity's sake, I've left out the implementation of InternalCheckIsWow64(), but that can be found here. Without this, I was running into issues with not finding the registry I wanted due to structural differences between 32- and 64-bit OSes.
Obligatory disclaimer -- play with the registry at your own peril.
This should point you in the right direction, but you're going to have to figure out the code:
look in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\ and you'll see a few sub keys corresponding to the interfaces in the "network connections" control panel. Probably only one will have a valid IP, and the others will have 0.0.0.0 You'll need to do some pattern matching to figure out which one is the right one.
get the key name for the interface (it's a GUID, or at least looks like one), and go back to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318} and check each one's NetCfgInstanceId value (or search) for the GUID of the interface.
Windows 10
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Class{4d36e972-e325-11ce-bfc1-08002be10318}\0004\NetworkAddress

Registry class. If key exist

Im using the Microsoft.Win32.Registry class. Im trying to make a if RegKey exist statement but don't know how
I want something like this:
RegistryKey key = Registry.CurrentUser.CreateSubKey(#"SOFTWARE\test");
if(key.keyExist("yourKey")) Console.WriteLine("yourKey exist!");
As far as I know, the SubKey is stored in a path in the system.
So you can do something like this to check out if the SubKey exists:
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\test"))
{
if (key != null)
{
Console.WriteLine("yourKey exist!");
}
else
{
// e.g. create SubKey
}
}

C# check and delete registry key problems

I'm trying to check (and delete) registry key. Code:
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
if (registryKey != null) // <- !!!!!!!!! problem is here, i think
{
registryKey.SetValue("MyApp", codeBase);
}
else
{
registryKey.DeleteValue("MyApp");
}
After creating value, application doesnt see new value and doesnt delete it.
What's wrong with this code? Thanks.
Your operations for adding and deleting from the registry look good just that there is an issue with your if-else condition. If you want to check and then delete a registry entry, you should do it like this:
string KeyName = #"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
string valueName = "MyApp";
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
if (Registry.GetValue(KeyName, valueName, null) != null)
{
RegistryKey registryKey = Registry.CurrentUser
.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
registryKey.DeleteValue(valueName);
}
Registry.GetValue(KeyName, valueName, null) is a better way to do a null check instead of doing registryKey != null because registryKey only gets the ..CurrentVersion\\Run subkey. Instead you should drill down the actual key for your app (eg. MyApp).
Hope this helps!

Attempting to delete registry keys with subkeys results in an error

When I try to delete a key in HKCU that has subkeys I get an error.
Here is the code I am using:
using (RegistryKey regkey = Registry.CurrentUser.OpenSubKey(#"Software\Policies\", true))
{
if (regkey.OpenSubKey("Google") != null)
{
regkey.DeleteSubKey("Google");
}
}
The error I get:
Registry key has subkeys and recursive removes are not supported by this method.
How can I overcome it?
Use the RegistryKey.DeleteSubKeyTree method.
RegistryKey.DeleteSubKeyTree Method (String)
Deletes a subkey and any child subkeys recursively.
using(RegistryKey regkey = Registry.CurrentUser.OpenSubKey(#"Software\Policies\", true))
{
if (regkey.OpenSubKey("Google") != null)
{
regkey.DeleteSubKeyTree("Google");
}
}
using(var regkey = Registry.CurrentUser.OpenSubKey(#"Software\Policies\", true))
{
regkey?.DeleteSubKeyTree("Google");
}

Categories