0

I have a file which has unicode of a byte array which is a serialized object. I tried reading that file using the code below.

string unicodeString = File.ReadAllText(filename);

This works fine, when i tried to get that Byte array back, for deserialization.

What I am looking for is, read only the particular lines of a file and try to convert that unicode string to bytes. For that I tried.

string unicodeString = string.join("", File.ReadAllLines(filename).Take(4).ToArray());

Here I used 4 because, the file has 4 lines of unicode string

byte[] _bytes = System.Text.Encoding.Unicode.GetBytes(unicodeString );

var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using (var ms = new MemoryStream(_bytes))
{
    myobject data = (myobject)bformatter.Deserialize(ms);
}

I can able to get the string but unable to deserialize. My objective is to I will many such objects in the file and I'll retrieve only those lines and deserialize that to object.

It throws the following exception.

{"Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization."}

Hafiz H
  • 399
  • 5
  • 22
  • 5
    Don't treat byte arrays that aren't strings as strings. Also, read [ask] and provide a [mcve]. The code you show does not throw that exception. You have an XY problem, where problem X is _"I want to serialize multiple objects into the same file"_, and your solution Y is _"I'll treat the serialized byte array as a string and store one serialized object per line"_. You went wrong with that solution and need to find a different approach. – CodeCaster Oct 04 '16 at 07:48
  • See for example [Serializing and Deserializing Multiple Objects](http://stackoverflow.com/questions/16416423/serializing-and-deserializing-multiple-objects). – CodeCaster Oct 04 '16 at 07:51
  • 3
    If you serialized the data it is binary and not a string. Never try to read a binary file with any text method it will corrupt the data. Use BinaryReader. – jdweng Oct 04 '16 at 07:57

0 Answers0