加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:39:02 所属栏目:百科 来源:网络整理
导读:我做了一些从流中编写文件的快速方法,但还没有完成.我收到此异常,我找不到原因: Unable to read beyond the end of the stream 有谁可以帮我调试吗? public static bool WriteFileFromStream(Stream stream,string toFile){ FileStream fileToSave = new F
我做了一些从流中编写文件的快速方法,但还没有完成.我收到此异常,我找不到原因:
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个字节).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读