c# – 无法读取超出流的末尾

前端之家收集整理的这篇文章主要介绍了c# – 无法读取超出流的末尾前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我做了一些从流中编写文件快速方法,但还没有完成.我收到此异常,我找不到原因:
  1. Unable to read beyond the end of the stream

有谁可以帮我调试吗?

  1. public static bool WriteFileFromStream(Stream stream,string toFile)
  2. {
  3. FileStream fileToSave = new FileStream(toFile,FileMode.Create);
  4. BinaryWriter binaryWriter = new BinaryWriter(fileToSave);
  5.  
  6. using (BinaryReader binaryReader = new BinaryReader(stream))
  7. {
  8. int pos = 0;
  9. int length = (int)stream.Length;
  10.  
  11. while (pos < length)
  12. {
  13. int readInteger = binaryReader.ReadInt32();
  14.  
  15. binaryWriter.Write(readInteger);
  16.  
  17. pos += sizeof(int);
  18. }
  19. }
  20.  
  21. return true;
  22. }

非常感谢!

解决方法

不是你的问题的答案,但这种方法可以这么简单:
  1. public static void WriteFileFromStream(Stream stream,string toFile)
  2. {
  3. // dont forget the using for releasing the file handle after the copy
  4. using (FileStream fileToSave = new FileStream(toFile,FileMode.Create))
  5. {
  6. stream.CopyTo(fileToSave);
  7. }
  8. }

请注意,我也删除了返回值,因为它几乎没用,因为在你的代码中,只有一个return语句

除此之外,您对流执行长度检查,但许多流不支持检查长度.

至于你的问题,首先要检查流是否在它的末尾.如果没有,你读4个字节.这是问题所在.假设您有一个6字节的输入流.首先,检查流是否在最后.答案是否定的,因为剩下6个字节.您读取4个字节并再次检查.当然,答案仍然是没有,因为剩下2个字节.现在你读了另外4个字节,但由于只有2个字节,因此会失败. (readInt32读取接下来的4个字节).

猜你在找的C#相关文章