Runtime error Attempting to deserialize an empty stream

依然范特西╮ 提交于 2019-12-14 03:02:54

问题


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.


回答1:


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.)



来源:https://stackoverflow.com/questions/25636260/runtime-error-attempting-to-deserialize-an-empty-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!