简体   繁体   English

如何使用 RegistryKey object 作为句柄删除注册表项

[英]How to delete registry key by using RegistryKey object as handle

I have a function (credit to @Charlieface ) that opens a registry symlink and returns a RegistryKey handle :我有一个 function (归功于@Charlieface ),它打开一个注册表符号链接并返回一个RegistryKey句柄

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
}

I want to delete this registry symlink by using the return handle of the key.我想通过使用密钥的返回句柄来删除这个注册表符号链接。
The functions that allows me to delete Registry keys require to provide the name of the key as a string, but in my case this is a symlink, it is not enough.允许我删除注册表项的功能需要提供键名作为字符串,但在我的情况下,这是一个符号链接,这还不够。
I have the RegistryKey handle as object and I want to delete it.我的RegistryKey句柄为 object,我想删除它。

I tried to delete it like that but it doesn't accept it:我试图像那样删除它,但它不接受它:

[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
}           

When I type key.当我键入key. I see that it as functions for deletion but it again asks for the key path as a string.我将其视为删除功能,但它再次要求将密钥路径作为字符串。

Undocumented but calling RegDeleteKey(hKey, @"") (advapi32) will delete a key by handle (works all the way back to Win95/NT4).未记录但调用RegDeleteKey(hKey, @"") (advapi32) 将通过句柄删除一个键(一直到 Win95/NT4)。

I don't know what the behavior on symlinks is.我不知道符号链接上的行为是什么。 It most likely deletes the link (if you specifically opened the symlink) and not the target but you just have to check to be sure.它很可能会删除链接(如果您专门打开了符号链接)而不是目标,但您只需检查以确保。

If you don't want to rely on undocumented behavior you have to call ZwDeleteKey (ntdll) as suggested by RbMm.如果您不想依赖未记录的行为,则必须按照 RbMm 的建议调用ZwDeleteKey (ntdll)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM