C# 无法读取流结尾以外的内容

C# 无法读取流结尾以外的内容,c#,stream,C#,Stream,我用了一些快速的方法从流中写入文件,但还没有完成。我收到此例外情况,但我无法找到原因: Unable to read beyond the end of the stream 有人能帮我调试吗 public static bool WriteFileFromStream(Stream stream, string toFile) { FileStream fileToSave = new FileStream(toFile, FileMode.Create); BinaryWr

我用了一些快速的方法从流中写入文件,但还没有完成。我收到此例外情况,但我无法找到原因:

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;
}
公共静态bool WriteFileFromStream(Stream-Stream,string-toFile)
{
FileStream fileToSave=newfilestream(toFile,FileMode.Create);
BinaryWriter BinaryWriter=新的BinaryWriter(fileToSave);
使用(BinaryReader BinaryReader=新的BinaryReader(流))
{
int pos=0;
int length=(int)stream.length;
while(pos
非常感谢

您正在执行while(pos试试看

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

我假设输入流只有int(Int32)。您需要测试
PeekChar()
方法

while (binaryReader.PeekChar() != -1)
{
  int readInteger = binaryReader.ReadInt32();
  binaryWriter.Write(readInteger);          
}

这并不是你问题的答案,但这种方法可以简单得多,如下所示:

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个字节)。

二进制读取器读取流后,流的位置在末尾,您必须将位置设置为零“stream.position=0;”

太棒了,就像您所说的那么简单!非常感谢:-)请注意,这根本没有效率
PeekChar
将实际保存主流中的当前位置,读取一个int,然后再次设置位置!