尝试删除注册表子键时抛出System.UnauthorizedAccessException异常求助
核心原因
你的代码调用Registry.LocalMachine.OpenSubKey()时未指定写入权限,默认以只读模式打开注册表键——即便程序以管理员身份运行,也无法执行删除操作。另外,遍历子键时打开的productKey未及时关闭,可能导致资源锁定,进一步阻碍删除操作。
修复步骤
- 以写入权限打开父键:调用
OpenSubKey时传入第二个参数true,明确申请写入权限 - 及时释放子键资源:使用
using语句包裹子键操作,确保用完自动关闭,避免锁定 - 添加异常捕获:处理删除过程中可能出现的其他异常(如子项被系统进程占用)
修复后的完整代码
static void Main(string[] args) { // 以写入权限打开父键,using自动释放资源 using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall", true)) { if (key == null) { Console.WriteLine("无法打开目标注册表路径"); Console.ReadLine(); return; } foreach (var childKey in key.GetSubKeyNames()) { // using包裹子键,确保用完关闭 using (RegistryKey productKey = key.OpenSubKey(childKey)) { if (productKey == null) continue; bool hasPublisherKey = productKey.GetValueNames().Any(x => x.Equals("Publisher", StringComparison.OrdinalIgnoreCase)); if (!hasPublisherKey) continue; var publisherValue = productKey.GetValue("Publisher")?.ToString(); if (!string.IsNullOrWhiteSpace(publisherValue) && publisherValue.Equals("HCI", StringComparison.OrdinalIgnoreCase)) { try { key.DeleteSubKeyTree(childKey); Console.WriteLine($"成功删除子键: {childKey}"); break; } catch (Exception ex) { Console.WriteLine($"删除失败: {ex.Message}"); } } } } Console.ReadLine(); } }
额外注意事项
- 确认程序确实以管理员身份运行:VS以管理员启动时,调试进程会自动继承权限,但需确保没有权限隔离问题
- 部分注册表子项可能被系统或其他进程锁定,此时
DeleteSubKeyTree仍会报错,建议保留异常捕获逻辑 - 若为64位程序且需访问64位注册表(非
Wow6432Node路径),可使用RegistryKey.OpenBaseKey指定RegistryView.Registry64
内容的提问来源于stack exchange,提问作者nikhil
相关产品推荐
相关产品推荐

