Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Setting Null Binary Values In The Registry With C#

0.00/5 (No votes)
13 Oct 2014 1  
How to set a null binary value (zero-length binary value) in the registry from your C# program.

Introduction

If you've ever tried to insert a null byte array or binary value programmatically into the Registry using the SetValue method available in the Registry functions provided in the Microsoft.Win32 namespace, you triggered an ArgumentNullException. However, it is possible to create an empty binary value or clear an existing one when using Registry Editor. Here's a simple way to do the same thing from your C# program.

Using the code

The key to this tip is C#'s null-coalescing operator. The ?? operator returns the left operand if it is not null. Otherwise, it returns the right operand. In the sample code below, I'm calling an encryption function for a password. This works fine for non-null passwords, but sometimes a password is not needed, in which case the encryption function returns null. Using ?? combined with an empty byte array successfully sets the value.

Registry Editor refers to a null byte value as a zero-length binary value. The code snippet below shows how to set a zero-length binary value with C# 2.0 or higher code.

// Store the password to the Registry. The Credentials argument to OpenSubKey contains the path
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(Credentials, true))
{
 // Encrypt the password and save it. Set it to empty binary if no password. PasswordTextBox
 // in this case was a WPF PasswordBox control. Encrypt is my AES encryption function, which
 // returns either an encrypted byte array or null if the password is empty

 byte[] encrypted = Encrypt(PasswordTextBox.Password);

 key.SetValue("Password", encrypted ?? new byte[]{ }, RegistryValueKind.Binary);
}

 

History

Original tip submitted 10/13/2014.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here