[英]Unable to read beyond the end of the stream
我做了一些从流中编写文件的快速方法,但还没有完成。 我收到此异常,我找不到原因:
Unable to read beyond the end of the stream
有谁可以帮我调试吗?
public static bool WriteFileFromStream(Stream stream, string toFile)
{
FileStream fileToSave = new FileStream(toFile, FileMode.Create);
BinaryWriter binaryWriter = new BinaryWriter(fileToSave);
using (BinaryReader binaryReader = new BinaryReader(stream))
{
int pos = 0;
int length = (int)stream.Length;
while (pos < length)
{
int readInteger = binaryReader.ReadInt32();
binaryWriter.Write(readInteger);
pos += sizeof(int);
}
}
return true;
}
非常感谢!
不是你的问题的答案,但这种方法可以这么简单:
public static void WriteFileFromStream(Stream stream, string toFile)
{
// dont forget the using for releasing the file handle after the copy
using (FileStream fileToSave = new FileStream(toFile, FileMode.Create))
{
stream.CopyTo(fileToSave);
}
}
请注意,我也删除了返回值,因为它几乎没用,因为在您的代码中,只有1个return语句
除此之外,您对流执行长度检查,但许多流不支持检查长度。
至于你的问题,首先要检查流是否在它的末尾。 如果没有,则读取4个字节。 这是问题所在。 假设您有一个6字节的输入流。 首先,检查流是否在最后。 答案是否定的,因为剩下6个字节。 您读取4个字节并再次检查。 当然,答案仍然是没有,因为剩下2个字节。 现在你读了另外4个字节,但由于只有2个字节,因此会失败。 (readInt32读取接下来的4个字节)。
我假设输入流只有int(Int32)。 你需要测试PeekChar()
方法,
while (binaryReader.PeekChar() != -1)
{
int readInteger = binaryReader.ReadInt32();
binaryWriter.Write(readInteger);
}
您正在执行while(pos <length),length是流的实际长度(以字节为单位)。 因此,您有效地计算流中的字节数,然后尝试读取多个整数(这是不正确的)。 您可以将长度设为stream.Length / 4,因为Int32是4个字节。
在通过二进制读取器读取流之后,流的位置在最后,您必须将位置设置为零“stream.position = 0;”
尝试
int length = (int)binaryReader.BaseStream.Length;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.