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.
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(Credentials, true))
{
byte[] encrypted = Encrypt(PasswordTextBox.Password);
key.SetValue("Password", encrypted ?? new byte[]{ }, RegistryValueKind.Binary);
}
History
Original tip submitted 10/13/2014.