Wednesday, April 6, 2011

how to delete registry value in c#

I can get/set registry value using Microsoft.Win32.Registry class. For example

Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", "MyApp", Application.ExecutablePath);

But i can't delete any value. How to delete registry value?

From stackoverflow
  • RegistryKey.DeleteValue

    ebattulga : how to get RegistryKey object
    ebattulga : DeleteValue is not static method
  • 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.

  •     RegistryKey registrykeyHKLM = Registry.LocalMachine;
        string keyPath = @"Software\Microsoft\Windows\CurrentVersion\Run\MyApp";
        registrykeyHKLM.DeleteValue(keyPath);
        registrykeyHKLM.Close();
    
    Sergey Mirvoda : non working code
    Binoj Antony : Corrected the mistake, it should work now.
  • 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);   
    }
    

0 comments:

Post a Comment