48

I am trying to deserialize a stream but I always get this error "End of Stream encountered before parsing was completed"?

Here is the code:

        //Some code here
        BinaryFormatter b = new BinaryFormatter();
        return (myObject)b.Deserialize(s);//s---> is a Stream object that has been fill up with data some line over here

Any one have ideas?

Mister Dev
  • 10,021
  • 12
  • 41
  • 33
  • In addition to the stream position issues pointed out below, another reason this can happen is because your app exits before a *large* file is written to disk (if you are serializing a large amount of data to a file stream). To fix this, you need to implement a blocking wait until the file is fully written like in this post: http://stackoverflow.com/questions/10982104/wait-until-file-is-completely-written – Special Sauce Dec 11 '15 at 19:26
  • 1
    For me removing saved data file from "C:\Users\\AppData\LocalLow\" fixed it because the problem was that I changed data models after saving the file which made the model of the existing data in file different and made it throw errors while deserializing it. Hope it helps. – ChiragMS Aug 23 '18 at 16:43

7 Answers7

66

Try to set the position to 0 of your stream and do not use your object but the object type.

        BinaryFormatter b = new BinaryFormatter();
        s.Position = 0;
        return (YourObjectType)b.Deserialize(s);
Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
  • 2
    Hi, I've same issue here, but after inserting s.Position =0; I get "Stream does not support seeking" – Jim Jul 18 '13 at 11:20
6

Make sure the serialization completed, and that the serialization type matches the de-serialization type (i.e., make sure you're serializing with a BinaryFormatter if you're de-serializing with one). Also, make sure that the stream you serialized to really finished serializing, with a Stream.Flush() or something to that effect.

GWLlosa
  • 23,995
  • 17
  • 79
  • 116
5

I had the same exception thrown, until I added the [Serializable] tag to the class I was Serializing :)

Then it all worked perfectly.

Ryano
  • 458
  • 4
  • 8
0

In my case I used:

stream.Seek(0, SeekOrigin.Begin);

after i serialized the stream, and before i deserialized the stream works charm. hope this helps!

Michael
  • 32,527
  • 49
  • 210
  • 370
Alia Ramli Ramli
  • 405
  • 6
  • 18
0

I have spent 5 hourse and have got end of stream error and lost data (Not obvious feature in GzipStream: you should use underlying stream only after flush GzipStream).

Full example of working code:

using System;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            string large = LargeJsonContent.GetBigObject();
            string base64;

            using (var readStream = new MemoryStream())
            using (var writeStream = new MemoryStream())
            {
                using (GZipStream compressor = new GZipStream(writeStream, CompressionMode.Compress, true)) //pay attention to leaveOpen = true
                {
                    var formatter = new BinaryFormatter();
                    formatter.Serialize(readStream, large);

                    Console.WriteLine($"After binary serialization of JsonString: {readStream.Length} bytes");

                    readStream.Position = 0;
                    readStream.CopyTo(compressor);
                }

                Console.WriteLine($"Compressed stream size: {writeStream.Length} bytes");

                writeStream.Position = 0;
                byte[] writeBytes = writeStream.ToArray();
                base64 = Convert.ToBase64String(writeBytes);
            }


            ////

            using (var stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, base64);
                Console.WriteLine($"Size of base64: {stream.Length} bytes");
            }

            Console.WriteLine("---------------------");
            ////

            string large2;

            var bytes = Convert.FromBase64String(base64);
            using (var readStream = new MemoryStream())
            {
                readStream.Write(bytes, 0, bytes.Length);
                readStream.Position = 0;
                Console.WriteLine($"Compressed stream size: {readStream.Length} bytes");
                using (var writeStream = new MemoryStream())
                {
                    using (GZipStream decompressor = new GZipStream(readStream, CompressionMode.Decompress, true)) //pay attention to leaveOpen = true
                    {
                        decompressor.CopyTo(writeStream);
                        writeStream.Position = 0;
                    }

                    var formatter = new BinaryFormatter();
                    large2 = (string)formatter.Deserialize(writeStream);
                }
            }

            Console.WriteLine(large == large2);
            Console.WriteLine($"large:{large.Length} | large2:{large2.Length}");
        }
    }
}

Yaroslav
  • 504
  • 6
  • 13
0

Check in your sender code if you are not doing the following

NetworkStream strm = client.GetStream(); // the stream
formatter.Serialize(strm, status); // the serialization process
strm.Close();// Remove this code, this was the culprit in my case
0

the class which you created must has [Serializable].

  • This is a duplicate answer; it is the same guidance as @Ryano offered five years ago. Please be sure to review all existing answers before contributing a new one. Later, once you have a bit more reputation, you'll be able to validate existing answers by upvoting them. – Jeremy Caney Apr 16 '22 at 00:47