Search code examples
c#registryfile-association

Deleting the icon associated with the file extension from the registry in C#


I use a method like this to associate the file extension with the icon:

public static void Associate(string extension, string progID, string description, string icon, string application)
{
    Registry.ClassesRoot.CreateSubKey(extension)?.SetValue("", progID);
    if (!string.IsNullOrEmpty(progID))
    {
        using var key = Registry.ClassesRoot.CreateSubKey(progID);
        if (description != null)
            key?.SetValue("", description);
        if (icon != null)
            key?.CreateSubKey("DefaultIcon")?.SetValue("", ToShortPathName(icon));
        if (application != null)
            key?.CreateSubKey(@"Shell\Open\Command")?.SetValue("", ToShortPathName(application) + " \"%1\"");
    }
}

When I want to completely delete the file extension that I have associated, I do not know how to proceed. For this, I tried something like this:

public static void Remove(string progID)
{
    Registry.ClassesRoot.DeleteSubKey(progID);
}

It gives an error like this:

The registry has subkeys and recursive removals are not supported by this method.


Solution

  • It has a solution at this address: https://www.codeproject.com/Articles/3389/Read-write-and-delete-from-registry-with-C

    Like this:

    public static RegistryKey BaseRegistryKey { get; set; } = Registry.LocalMachine;
    public static string subKey { get; set; } = "SOFTWARE\\" + Application.ProductName.ToUpper();
    
    public bool DeleteSubKeyTree()
    {
        try
        {
            // Setting
            RegistryKey rk = baseRegistryKey ;
            RegistryKey sk1 = rk.OpenSubKey(subKey);
            // If the RegistryKey exists, I delete it
            if ( sk1 != null )
                rk.DeleteSubKeyTree(subKey);
    
            return true;
        }
        catch (Exception e)
        {
            // AAAAAAAAAAARGH, an error!
            MessageBox.Show(e, "Deleting SubKey " + subKey);
            return false;
        }
    }