gpt4 book ai didi

c# - 无法读取超出流末尾的内容

转载 作者:太空狗 更新时间:2023-10-29 21:24:13 25 4
gpt4 key购买 nike

我做了一些快速的方法来从流中写入文件,但还没有完成。我收到此异常,但找不到原因:

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 个返回语句

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

至于您的问题,您首先要检查流是否已结束。如果不是,则读取 4 个字节。这就是问题所在。假设您有一个 6 字节的输入流。首先,您检查流是否已结束。答案是否定的,因为还剩下 6 个字节。您读取 4 个字节并再次检查。当然答案仍然是否定的,因为还剩下 2 个字节。现在你又读了 4 个字节,但当然失败了,因为只有 2 个字节。 (readInt32 读取接下来的 4 个字节)。

关于c# - 无法读取超出流末尾的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7815754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com