Deleting a 64 bit registry entry from a 32 bit app in C#.

Okay, this may be old hat to some of you, but it took me some time to figure it out and I didn't find much useful when searching.

Came across a need to delete a 64 bit registry value from a 32 bit app.  The standard registry delete functions would end up deleting it from the Wow6432Node, which was what was not the desired outcome.

The code to make it happen is pretty simple, but I've got no error checking in the sample code here:

First, the P/Invoke stuff:

 [DllImport("advapi32.dll")]

static extern int RegOpenKeyEx(

      RegistryHive hKey,

      [MarshalAs(UnmanagedType.VBByRefStr)] ref string subKey,

      int options,

      int sam,

      out UIntPtr phkResult );

 [DllImport("advapi32.dll")]

static extern int RegDeleteValue(

      UIntPtr hKey,

      [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpValueName

      );

And then, the meat of the program:

      UIntPtr KeyHandle = UIntPtr.Zero;

      string key = @"Software\Microsoft\Windows NT\CurrentVersion\TestKey";

      string value = "DeleteThisValue";

      RegOpenKeyEx(RegistryHive.LocalMachine,ref key,0,0x000f013f,out KeyHandle);

      RegDeleteValue(KeyHandle,ref value);

The magic numbers 0 and 0x000f103f shouldn't be hardcoded; the 0 is "Non-volatile registry" and the hex number is both "KEY_WOW64_64KEY" (0x100) and "KEY_ALL_ACCESS (0xf003f)".

This article is part of the GWB Archives. Original Author: derekf

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.