Sabbir Ahmed Sabbir Ahmed - 1 month ago 6
C# Question

How to return from deleting if registry key doesn't exist?

I want to delete registry value but if doesn't exist then return.

How can possible??

Example:

>>> For inserting <<<

private void startup_Click(object sender, RoutedEventArgs e)
{
Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", "MyApp", System.Windows.Forms.Application.ExecutablePath);
}


>>> For Deleting<<<

private void DeleteRegKey_Click(object sender, RoutedEventArgs e)
{
string keyName = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName , true))
{
if (key != null)
{
key.DeleteValue("MyApp");

}
else
{

System.Windows.MessageBox.Show("Not Found!", "Error", MessageBoxButton.OK);

}

}
}


It's working fine if file exist but failed if doesn't exist.

Please help me.

Answer

Put a check before doing actual delete

if(key.GetValue("MyApp") != null)    
    key.DeleteValue("MyApp");
else
   // do something if value doesn't exist
Comments