Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to read beyond the end of the stream

Tags:

c#

stream

I did some quick method to write a file from a stream but it's not done yet. I receive this exception and I can't find why:

Unable to read beyond the end of the stream

Is there anyone who could help me debug it?

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

Thanks a lot!

like image 979
Tommy B. Avatar asked Oct 19 '11 01:10

Tommy B.


1 Answers

Not really an answer to your question but this method could be so much simpler like this:

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

Note that i also removed the return value since its pretty much useless since in your code, there is only 1 return statement

Apart from that, you perform a Length check on the stream but many streams dont support checking Length.

As for your problem, you first check if the stream is at its end. If not, you read 4 bytes. Here is the problem. Lets say you have a input stream of 6 bytes. First you check if the stream is at its end. The answer is no since there are 6 bytes left. You read 4 bytes and check again. Ofcourse the answer is still no since there are 2 bytes left. Now you read another 4 bytes but that ofcourse fails since there are only 2 bytes. (readInt32 reads the next 4 bytes).

like image 92
Polity Avatar answered Sep 28 '22 09:09

Polity