0

I have this piece of code to deserialize a serialized list of Animals. However i get the End of Stream encountered before parsing was completed, error. Do any of you have a solution to this? I cant seem to figure it out by myself.

public void Load(String fileName)
{
if (fileName == null)
{
    throw new ArgumentNullException("fileName");
}
String path = @"C:" + fileName;
if (fileName.Contains(@"\"))
{
    path = fileName;
}
using (FileStream fileStream = File.OpenRead(path))
{
    BinaryFormatter format = new BinaryFormatter();
    
    object obj = format.Deserialize(fileStream);
    if (obj.GetType() == typeof(List<Animal>))
    {
        List<Animal> Animals = (List<Animal>)format.Deserialize(fileStream);
    }               
}
}


public void Save(String fileName)
    {
        if (fileName == null)
        {
            throw new ArgumentNullException("fileName");
        }
        String path = @"C:" + fileName;
        if (fileName.Contains(@"\"))
        {
            path = fileName;
        }
        using (FileStream fileStream = File.Open(path, FileMode.Create))
        {
            BinaryFormatter format = new BinaryFormatter();
            format.Serialize(fileStream, Animals);
        }
    }
  • It sounds like the file is corrupted. – ProgrammingLlama May 30 '21 at 14:18
  • You had to use the exact same class to deserialize that you use to serialize. If you modfied the class you will get an exception. – jdweng May 30 '21 at 14:30
  • @jdweng i dont really know what you mean, ive added the serializing method aswell. Does this clarify? –  May 30 '21 at 15:47
  • You have a variation on the "failed to reset stream position to 0" error. In your case, you needlessly induced the error by trying to deserialize from the same stream twice. If you want to do that, you have to set the stream's `Position` property to 0 before the second time. But there's no need to deserialize twice. Just case: `Animals = (List)obj;`. Note also that you should not include the variable's type in that statement; in your cod above you are _redeclaring_ the `Animals` variable locally...setting the _local_ variable that way will leave your class field _not_ set. – Peter Duniho May 30 '21 at 15:57

0 Answers0