【问题标题】:EndOfStreamException with simple BinaryWriter and BinaryReader带有简单 BinaryWriter 和 BinaryReader 的 EndOfStreamException
【发布时间】:2015-04-21 08:16:32
【问题描述】:

我正在使用以下代码:

var fileStream = new MemoryStream();
var binaryWriter = new BinaryWriter(fileStream);
var binaryReader = new BinaryReader(fileStream);

binaryWriter.Write("Hello");
var msg = binaryReader.ReadString();

但是我得到以下异常:

System.IO.EndOfStreamException: Unable to read beyond the end of the stream.

在读取之前,binaryReader.BaseStream.Length 大于 0,但 binaryReader.PeekChar() 返回 -1。

我做错了什么?

【问题讨论】:

  • 我手头没有C# 编译器,但这可能是因为您没有将写入的数据Flushing 到底层设备。写信后尝试输入binaryWriter.Flush()
  • Flush() 不起作用。问题确实出在职位上。

标签: c# serialization memorystream binaryreader binarywriter


【解决方案1】:

在您写入流后,流的位置将与您写入的任何内容的长度相同。

为了在写入后直接从中读取,您必须重置流的位置:

binaryWriter.Write("Hello");
binaryWriter.BaseStream.Position = 0;
var msg = binaryReader.ReadString();

将导致写入流的原始“Hello”被分配给msg

【讨论】:

    猜你喜欢
    • 2018-08-21
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 2016-05-26
    • 2016-03-20
    相关资源
    最近更新 更多