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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With