2011-10-19 111 views
6

我做了一些快速的方法来从流中写入文件,但尚未完成。我收到这个例外,我找不到原因:无法读取超过流末尾

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

非常感谢!

回答

5

不是一个真正的回答你的问题,但这种方法也能像这样简单的这么多:

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

+0

令人惊叹,像你说的那么简单!非常感谢 :-) – TomShreds

1

您正在做while(pos <长度),length是流的实际长度(以字节为单位)。因此,您正在有效地计算流中的字节数,然后尝试读取很多整数(这是不正确的)。因为Int32是4个字节,所以你可以把长度设为stream.Length/4。

0

尝试

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

我假定输入流中有仅整数(Int32)已。你需要测试PeekChar()方法,

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

请注意,这根本没有效率。 'PeekChar'实际上会保存主流中的当前位置,读取一个int,然后再次设置位置! –

0

在通过二进制阅读器读取流之后,流的位置在最后,必须将位置设置为零“stream.position = 0;”