user195488
user195488

Reputation:

Convert object to byte[]

I am trying to convert a retrieved registry value from object to byte[]. It is stored as REG_BINARY. I tried using BinaryFormatter with MemoryStream. However, it adds overhead information that I do not want. I observed this when I then converted the byte array to a string by performing the function Convert.ToBase64String(..). I am performing these functions because I am testing the storing and retrieval of an encrypted key in the registry.

Upvotes: 1

Views: 12216

Answers (3)

csauve
csauve

Reputation: 6263

Try this. If it already is a REG_BINARY, all you need to do is cast it:

static byte[] GetFoo()
{

  var obj = Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\Software", "foo", null);
  //TODO: Write a better exception for when it isn't found
  if (obj == null) throw new Exception(); 

  var bytearray = obj as byte[];
  //TODO: Write a better exception for when its found but not a REG_BINARY
  if (bytearray == null) throw new Exception(); 

  return bytearray;
}

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500225

If it's a REG_BINARY then it should already be a byte array when you retrieve it... can't you just cast it to byte[]?

Alternatively, if you haven't already verified that it's REG_BINARY in the code, you may want to use:

byte[] binaryData = value as byte[];
if (binaryData == null)
{
    // Handle case where value wasn't found, or wasn't binary data
}
else
{
    // Use binaryData here
}

Upvotes: 8

Steve Danner
Steve Danner

Reputation: 22148

If you converted it using Convert.ToBase64String, you should be able to get it out similarly.

string regValueAsString = (string)regValueAsObj;
byte[] buf = Convert.FromBase64String(regValueAsString);

Upvotes: 0

Related Questions