Search code examples
c#winapiregistryregistrykey

How to import ZwDeleteKey in C#: "External component has thrown an exception"


I am trying to use ZwDeleteKey to delete a registry symbolic link.
I imported it like that:

[DllImport("NtosKrnl.exe", CharSet = CharSet.Ansi, EntryPoint = "ZwDeleteKey", SetLastError = true)]  
private static extern int ZwDeleteKey(SafeRegistryHandle hKey);  

But after I call it, I receive an exception:

"External component has thrown an exception"

My full code:

[DllImport("NtosKrnl.exe", CharSet = CharSet.Ansi, EntryPoint = "ZwDeleteKey", SetLastError = true)]  
private static extern int ZwDeleteKey(SafeRegistryHandle hKey);  

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);
}  


static void Main(string[] args)
{
    RegistryKey key;
    key = OpenSubKeySymLink(Microsoft.Win32.Registry.CurrentUser, @"SOFTWARE\Microsoft\Windows\ABC", RegistryRights.ReadKey, 0);
    ZwDeleteKey(key.Handle);
}


Solution

  • Official documentation for ZwDeleteKey does mention "NtosKrnl.exe" being the "DLL", but this is wrong, the import definition should be like this instead (plus there's no string involved, the entry point is not ambiguous and the function doesn't set last error):

    [DllImport("ntdll")]
    private static extern int ZwDeleteKey(SafeRegistryHandle hKey);