使用 C# 删除注册表项

Delete a Registry key using C#

我正在尝试删除这样的注册表项:

RegistryKey oRegistryKey = Registry.CurrentUser.OpenSubKey(
    "Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts", true);

oRegistryKey.DeleteSubKeyTree(".");

但这给了我一个例外:

Cannot delete a subkey tree because the subkey does not exist

如果我将 DeleteSubKeyTree 更改为 DeleteSubKey,我会收到不同的异常:

Registry key has subkeys and recursive removes are not supported by this method

试试这个:

string str = @"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts";
string[] strSplit = strLocal.Split('\');
            using (RegistryKey oRegistryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts", true))
            {
                RegistryKey hdr = oRegistryKey.OpenSubKey(strSplit[strSplit.Length-2], true);
                foreach (String key in hdr.GetSubKeyNames())
                    hdr.DeleteSubKey(key);
                hdr.Close();
                oRegistryKey.DeleteSubKeyTree(strSplit[strSplit.Length - 2]);
            }

同时检查:Registry in .NET: DeleteSubKeyTree says the subkey does not exists, but hey, it does!

首先您需要检查注册表项:

using (RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts"))
    if (Key != null)
    {    
       key.DeleteValue("."); //delete if exist
    }
    else
    {
        MessageBox.Show("key not found");
    }

这对你有帮助......

http://www.codeproject.com/Questions/166232/C-delete-a-registry-key-cannot-get-it-done

is needlessly complex because DeleteSubKeyTree 中概述的方法是递归的。来自其在 MSDN 上的文档:

Deletes a subkey and any child subkeys recursively.

因此,如果您的目标是删除用户的 FileExts 密钥,请执行以下操作:

string explorerKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Explorer";

using (RegistryKey explorerKey =
    Registry.CurrentUser.OpenSubKey(explorerKeyPath, writable: true))
{
    if (explorerKey != null)
    {
        explorerKey.DeleteSubKeyTree("FileExts");
    }
}

但是,您确定真的要删除用户的 FileExts 密钥吗?我相信大多数人会认为这样做是不合理的破坏性和鲁莽行为。更常见的情况是从 FileExts 键中删除 单个文件扩展键 (例如 .hdr)。

最后,请注意 DeleteSubKeyTree 已过载。这是此方法的 second version 的签名:

public void DeleteSubKeyTree(
    string subkey,
    bool throwOnMissingSubKey
)

对于这个版本,如果 subkey 不存在且 throwOnMissingSubKey 为假,DeleteSubKeyTree 将简单地 return 而不对注册表进行任何更改。

请注意32位或64位注册表。 注意:RegistryView.Registry64这是问题的关键。

这是适合我的实现:

public static void DeleteRegistryFolder(RegistryHive registryHive, string fullPathKeyToDelete)
{
    using (var baseKey = RegistryKey.OpenBaseKey(registryHive, RegistryView.Registry64))
    {
        baseKey.DeleteSubKeyTree(fullPathKeyToDelete);
    }
}

用法:

var baseKeyString = $@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\MyApp";

DeleteRegistryFolder(RegistryHive.LocalMachine, baseKeyString);

如果 'subkey' 参数为空字符串,DeleteSubKeyDeleteSubKeyTree 两种方法都会删除当前密钥,例如 key.DeleteSubKey("");

密钥应具有写入权限。 它必须是 closed/disposed 常规方式。