运行时错误尝试反序列化空流 [英] Runtime error Attempting to deserialize an empty stream

查看:617
本文介绍了运行时错误尝试反序列化空流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试反序列化文件中的字符串列表。这是我的代码

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.

推荐答案

如果要支持空文件,请首先检查是否文件为空:

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

这篇关于运行时错误尝试反序列化空流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆