C# check and delete registry key problems - c#

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!

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.

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
}
}

Why is OpenSubKey() returning null on my Windows 10 64-bit system?

I'm developing x86 app to translate self-created "programming language" to assembler. At some point I need to get path to MASM32. I have read a couple of related topics, but they didn't help me, maybe because I'm new to C#.
MASM32 is situated here:HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MASM32.
When I run my program, I always get "Masm32 is not found" message.
What should I do? Thanks in advance!
WindowsIdentity ident = WindowsIdentity.GetCurrent();
WindowsPrincipal myPrincipal = new WindowsPrincipal(ident);
if (!myPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
string user = Environment.UserDomainName + "\\" + Environment.UserName;
RegistrySecurity rs = new RegistrySecurity();
rs.AddAccessRule(new RegistryAccessRule(user,
RegistryRights.ReadKey | RegistryRights.Delete | RegistryRights.CreateSubKey | RegistryRights.WriteKey | RegistryRights.ChangePermissions | RegistryRights.SetValue,
InheritanceFlags.None,
PropagationFlags.None,
AccessControlType.Deny));
}
try
{
RegistryKey baseKey = RegistryKey.OpenBaseKey(
RegistryHive.LocalMachine,
RegistryView.Registry64);
RegistryKey key = baseKey.OpenSubKey(#"SOFTWARE\Wow6432Node\");
PathMasm32 = baseKey.GetValue("MASM32").ToString();
}
catch {
erTxt = "Masm32 is not found";
}
It is probably not OpenSubKey() that is causing the null reference exception, but the baseKey.GetValue().ToString() call. The baseKey.GetValue() returns null (because in that case you are trying to get a value right under the HKEY_LOCAL_MACHINE root node) and you invoke ToString() on a null reference. Instead of baseKey.GetValue(), you should try key.GetValue(), assuming MASM32 is really a value under HKLM\SOFTWARE\Wow6432Node which is highly unlikely.
key.GetValue("MASM32").ToString();
Security Note: If you are looking for the installation path of MASM32, even though I do not have any expertise on that, they clearly state that The MASM32 SDK is registry safe and writes nothing to the registry.
Thus, MASM32 is probably a KEY not a VALUE, therefore please execute this method and print the output of it, and you will see the key/value pairs registered under the MASM32 key assuming it exists at the registry path HKLM\SOFTWARE\Wow6432Node\MASM32
public static string GetMASM32LocationFromRegistry()
{
RegistryKey localMachineRegistryKey;
RegistryKey masm32RegistryKey;
RegistryView currentRegistryView = RegistryView.Registry64;
localMachineRegistryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, currentRegistryView);
masm32RegistryKey = localMachineRegistryKey.OpenSubKey(#"SOFTWARE\Wow6432Node\MASM32");
if (masm32RegistryKey == null)
{
return #"ERROR: The registry key HKLM\SOFTWARE\Wow6432Node\MASM32 could not be found";
}
StringBuilder masm32RegistryKeyValuesBuilder = new StringBuilder("Key/Value pairs for registry key HKLM\\SOFTWARE\\Wow6432Node\\MASM32:\r\n");
foreach (string masm32RegistryKeyValueName in masm32RegistryKey.GetValueNames())
{
masm32RegistryKeyValuesBuilder.AppendFormat
(
"Key: [{0}], Value: [{1}], Value Type: [{2}]\r\n",
masm32RegistryKeyValueName,
masm32RegistryKey.GetValue(masm32RegistryKeyValueName),
masm32RegistryKey.GetValueKind(masm32RegistryKeyValueName)
);
}
return masm32RegistryKeyValuesBuilder.ToString();
}

Delete Registry Subkey C# [duplicate]

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.

Find and Read registry key within CLR

I need to check the availability and also read some registry key by CLR(C#), registry keys already written by another application.
As a sample:
public bool IsKeyAvailable(string KeyID)
{
string keyToRead = #"Software\myRoot\myApp\" + KeyID;
using (RegistryKey regKey = Registry.CurrentUser.OpenSubKey(keyToRead, RegistryKeyPermissionCheck.ReadSubTree))
{
if (regKey == null)
return false;
return true;
}
}
Checking & reading code are working fine outside of the CLR, but within the CLR the same code doesn't working, Already signed the CLR and assembly created WITH PERMISSION_SET = UNSAFE.
What could be missed for this scenario to find and read my registry keys by CLR?
Use this code :
Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
RegistryKey masterKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\yourapp\yourkey");
string value = "";
if (masterKey != null)
{
value = masterKey.GetValue("yourvalue").ToString();
}
masterKey.Close();

Categories