3

I am trying to deserialize an list of string from a file. Here my code

FileStream filestream = new FileStream(@"D:\cache.bin", FileMode.OpenOrCreate);
try
{
    BinaryFormatter binformat = new BinaryFormatter();
    _cacheFileList = (List<string>)binformat.Deserialize(filestream);
}
catch (SerializationException ex)
{
    Console.WriteLine(ex.Message);
}
finally 
{
    filestream.Close();
}

I am getting a Runtime error. Attempting to deserialize an empty stream.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
Sowvik Roy
  • 885
  • 2
  • 11
  • 25

1 Answers1

11

If you want support for empty files, first check if the file is empty:

if (filestream.Length == 0)

If it is, initialise your data. If it isn't, deserialise from the file. (Note that the content of the file should be the result of serialisation.)

Sam
  • 40,644
  • 36
  • 176
  • 219