我做了一些从流中编写文件的快速方法,但还没有完成.我收到此异常,我找不到原因:
- 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);
- }
- }
请注意,我也删除了返回值,因为它几乎没用,因为在你的代码中,只有一个return语句
除此之外,您对流执行长度检查,但许多流不支持检查长度.
至于你的问题,首先要检查流是否在它的末尾.如果没有,你读4个字节.这是问题所在.假设您有一个6字节的输入流.首先,检查流是否在最后.答案是否定的,因为剩下6个字节.您读取4个字节并再次检查.当然,答案仍然是没有,因为剩下2个字节.现在你读了另外4个字节,但由于只有2个字节,因此会失败. (readInt32读取接下来的4个字节).