如何使用 RegistryKey 对象作为句柄删除注册表项
How to delete registry key by using RegistryKey object as handle
我有一个函数(归功于 @Charlieface)可以打开注册表符号链接和 returns RegistryKey
handle:
public static RegistryKey OpenSubKeySymLink(this RegistryKey key, string name, RegistryRights rights = RegistryRights.ReadKey, RegistryView view = 0)
{
var error = RegOpenKeyExW(key.Handle, name, REG_OPTION_OPEN_LINK, ((int)rights) | ((int)view), out var subKey);
if (error != 0)
{
subKey.Dispose();
throw new Win32Exception(error);
}
return RegistryKey.FromHandle(subKey); // RegistryKey will dispose subKey
}
我想使用密钥的 return 句柄删除此注册表符号链接。
允许我删除注册表键的函数需要提供键的名称作为字符串,但在我的例子中,这是一个符号链接,这还不够。
我有 RegistryKey
句柄作为对象,我想删除它。
我试过那样删除它,但它不接受:
[DllImport("advapi32.dll", EntryPoint = "RegDeleteKeyEx", SetLastError = true)]
public static extern int RegDeleteKeyEx(
UIntPtr hKey,
string lpSubKey,
uint samDesired, // see Notes below
uint Reserved);
static void Main(string[] args)
{
RegistryKey key;
key = OpenSubKeySymLink(Microsoft.Win32.Registry.CurrentUser, @"SOFTWARE\Microsoft\Windows\ABC", RegistryRights.ReadKey, 0);
RegDeleteKeyEx(key, @"SOFTWARE\Microsoft\Windows\ABC", 0x100, 0); // don't know how to delete the RegistryKey handle
}
当我键入 key.
时,我看到它作为删除函数,但它再次要求以字符串形式输入密钥路径。
未记录但调用 RegDeleteKey(hKey, @"")
(advapi32) 将通过句柄删除密钥(一直有效到 Win95/NT4)。
我不知道 symlinks 上的行为是什么。它很可能会删除 link(如果您专门打开了 symlink)而不是目标,但您只需要检查一下即可。
如果您不想依赖未记录的行为,您必须按照 RbMm 的建议调用 ZwDeleteKey
(ntdll)。
我有一个函数(归功于 @Charlieface)可以打开注册表符号链接和 returns RegistryKey
handle:
public static RegistryKey OpenSubKeySymLink(this RegistryKey key, string name, RegistryRights rights = RegistryRights.ReadKey, RegistryView view = 0)
{
var error = RegOpenKeyExW(key.Handle, name, REG_OPTION_OPEN_LINK, ((int)rights) | ((int)view), out var subKey);
if (error != 0)
{
subKey.Dispose();
throw new Win32Exception(error);
}
return RegistryKey.FromHandle(subKey); // RegistryKey will dispose subKey
}
我想使用密钥的 return 句柄删除此注册表符号链接。
允许我删除注册表键的函数需要提供键的名称作为字符串,但在我的例子中,这是一个符号链接,这还不够。
我有 RegistryKey
句柄作为对象,我想删除它。
我试过那样删除它,但它不接受:
[DllImport("advapi32.dll", EntryPoint = "RegDeleteKeyEx", SetLastError = true)]
public static extern int RegDeleteKeyEx(
UIntPtr hKey,
string lpSubKey,
uint samDesired, // see Notes below
uint Reserved);
static void Main(string[] args)
{
RegistryKey key;
key = OpenSubKeySymLink(Microsoft.Win32.Registry.CurrentUser, @"SOFTWARE\Microsoft\Windows\ABC", RegistryRights.ReadKey, 0);
RegDeleteKeyEx(key, @"SOFTWARE\Microsoft\Windows\ABC", 0x100, 0); // don't know how to delete the RegistryKey handle
}
当我键入 key.
时,我看到它作为删除函数,但它再次要求以字符串形式输入密钥路径。
未记录但调用 RegDeleteKey(hKey, @"")
(advapi32) 将通过句柄删除密钥(一直有效到 Win95/NT4)。
我不知道 symlinks 上的行为是什么。它很可能会删除 link(如果您专门打开了 symlink)而不是目标,但您只需要检查一下即可。
如果您不想依赖未记录的行为,您必须按照 RbMm 的建议调用 ZwDeleteKey
(ntdll)。