Search code examples
c#registry

How to delete a registry value in 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?


Solution

  • 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.