I am trying to convert a retrieved registry value from object
to byte[]
. It is stored as REG_BINARY
. I tr开发者_StackOverflowied 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.
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
}
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;
}
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);
精彩评论