Scenario: I’m about to implement a caching functionality in which I want to cache a serialized object tree that I’ve received from a web service. The serialized object comes as a byte[] and I basically just want to create a 2nd byte[] that I want to store in case I want to restore the original data without querying the web service again.
Problem: If I copy the source byte[] into the target byte[] by using a simple loop, like:
for (int i = 0; i < source.Length - 1; i++)
target[i] = source[i];
then the BinaryFormatter is not able to deserialize that new byte[]. The exception says:
Binary stream ‘0’ does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.
But if I copy the arrays using Buffer.BlockCopy() or Array.CopyTo() the BinaryFormatter has no problems to deserialize the copied byte[].
So my question is, does anyone know why and how copying that array in a loop differs from using those functions? What exactly is missing from that byte[] in the first approach?
Look at this:
That’s copying all but the last byte. You want:
It would be simpler just to call
Clone()though: