无法读取流末尾以外的内容

本文关键字:读取 | 更新日期: 2023-09-27 18:11:34

我做了一些从流写入文件的快速方法,但它还没有完成。我收到这个异常,我不知道为什么:

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);
    }
} 

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

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

对于你的问题,你首先检查流是否在它的末端。如果不是,则读取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

try

int length = (int)binaryReader.BaseStream.Length;

通过二进制读取器读取流后,流的位置位于末尾,您必须将位置设置为零"stream.position=0;"