Click here to Skip to main content
15,910,878 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've been reading stuff from a stream using BinaryReader in the normal way and I don't know how big the stream is - I don't care but I need to know when I get to the end, so I've been doing this:

C#
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
    // do stuff
}


Now, as an enhancement I've compressed the data coming in and have attached a DeflateStream (with option inflate) between the previous stream and the reader:

using (DeflateStream inflation = new DeflateStream(stream, CompressionMode.Decompress, true))
{
    // create reader etc. as before
}


But now this doesn't work as neither Position or Length is supported on a DeflateStream. That makes sense as you'll never know how big it is until you've finished decompressing it. What I would expect to be able to do is tell whether I'm at the end or not.

At the moment, I know because it throws an exception. There has to a better way?
Posted
Comments
Bernhard Hiller 2-Sep-13 10:44am    
What do you think of reader.Peek()?
Rob Philpott 2-Sep-13 11:05am    
Thanks for the suggestion, but unfortunately that always returns -1 when the underlying stream doesn't support seeking, which DeflateStream doesn't. Hence it always reports end of stream!

1 solution

As you say the stream can't know it's size so the usual strategy for reading from a stream won't work. I found this SO solution http://stackoverflow.com/questions/1528508/uncompress-data-file-with-deflatestream[^].

Inside an "infinite" loop you keep reading:

C#
using (DeflateStream inflation = new DeflateStream(stream, CompressionMode.Decompress, true))
{
    byte[]  buffer = new byte[BUF_SIZE];
    while(true)
    {
        int lengthRead = inp.Read(buffer, 0, buffer.Length)
        if(lengthRead <= 0)
             break;
        // Transfer from buffer, but only transfer the first "lengthRead" number of bytes to prevent "overruns" in the final iteration.
    }
}



BUF_SIZE is the size of the buffer you want to use. I haven't used this before, so apologies in advance if it fails (can't test right now) but hopefully this should get you re-started.
 
Share this answer
 
Comments
Rob Philpott 3-Sep-13 14:23pm    
That's a way, but also the thing I was trying to avoid (ie. reading into a buffer). I just want to use BinaryReader to extract primitives from it so this complicates that. That said, it is a solution and probably the only one by the looks (I am surprised such a simple thing is not supported) so answer accepted and thanks for taking the time to have a look into it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900