Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading