Search code examples
c#objectarraysmemorystreambinaryformatter

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.


Solution

  • 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
    }