我正在尝试删除这样的注册表项:
RegistryKey oRegistryKey = Registry.CurrentUser.OpenSubKey(
"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts", true);
oRegistryKey.DeleteSubKeyTree(".");
但这给了我一个例外:
无法删除子项树,因为该子项不存在
如果我将DeleteSubKeyTree
更改为DeleteSubKey
,我会收到一个不同的例外:
注册表项具有子项,此方法不支持递归删除
答案 0 :(得分:2)
this answer中概述的方法不必要地复杂,因为DeleteSubKeyTree是递归的。从其MSDN上的文档:
递归删除子项和子子项。
因此,如果您的目标是删除用户的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
为false,则DeleteSubKeyTree
只会在不对注册表进行任何更改的情况下返回。
答案 1 :(得分:1)
试试这个:
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!
答案 2 :(得分:0)
首先,您需要检查注册表项:
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");
}
答案 3 :(得分:0)
这很简单。 关闭注册表。 重新打开它。 你不会找到“。”名字键他们的。 因为它在您第一次尝试时已被删除。
创建一个名为“。”的新密钥。并尝试使用相同的代码删除(两次)。 你会找到答案
答案 4 :(得分:0)
这会帮助你............
http://www.codeproject.com/Questions/166232/C-delete-a-registry-key-cannot-get-it-done
答案 5 :(得分:0)
请注意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);