Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatter deserialize gives: End of Stream encountered before parsing was completed

I am trying to deserialize an object I saved to a file (with Binary Formatter). Whatever I try, I get the exception: End of Stream encountered before parsing was completed

I have the following lines of code:

public static T DeserializeFromBinaryFile<T>(string fileName)
{
    T instance = default(T);
    FileStream fs = new FileStream(fileName, FileMode.Open);
    try
    {
        BinaryFormatter formatter = new BinaryFormatter();
        instance = (T)formatter.Deserialize(fs);
    }
    catch{}
    finally
    {
        fs.Close();
    }

    return instance;
}

I also tried:

public static T DeserializeFromBinaryFile<T>(string fileName)
{
    T instance = default(T);
    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    MemoryStream ms = new MemoryStream();
    try
    {
        byte[] bytes = new byte[fs.Length];
        fs.Read(bytes, 0, (int)fs.Length);
        ms.Write(bytes, 0, (int)fs.Length);
        ms.Position = 0;
        ms.Seek(0, SeekOrigin.Begin); 
    }
    catch { }

    try
    {
        BinaryFormatter formatter = new BinaryFormatter();
        instance = (T)formatter.Deserialize(ms);
    }
    catch { }
    finally
    {
        ms.Close();
        fs.Close();
    }

    return instance;
}

But whatever I do, always get the exception:

End of Stream encountered before parsing was completed

ADDITION: I just did some extra tests. If I have a simple object, just a few properties, it works just fine. Using a more (big) complex object, having other objects, enums, etc. encapsulated, that's when I get the exception.

like image 605
royu Avatar asked Apr 02 '13 13:04

royu


1 Answers

Try to set the position to 0 for your stream, inside of the second try/catch block:

BinaryFormatter b = new BinaryFormatter();
s.Position = 0;
return (YourObjectType)b.Deserialize(s);
like image 139
Otacon Avatar answered Nov 14 '22 21:11

Otacon