views:

170

answers:

2

Hi there!

I have a class, that wrapps a Stream instance, so I can use it for wrapping FileStreams and NetworkStreams. Now, I want to test if the stream is still delivering any data, in other words, I want to test the NetworkStream if it is still connected or the FileStream if it reached its end.

Is there any function whose return value I can use to determine if the next Stream.Read() will cause an exception?

Thanks in advance.

A: 
stream.CanRead
Mehrdad Afshari
+1  A: 

Stream.Read shouldn't throw an exception at the end; it returns something non-positive. I just Read(...) until I get back this - i.e.

int read;
while((read = stream.Read(buffer, 0, buffer.Length) > 0) {
    // process "read"-many bytes
}

Note that NetworkStream has a DataAvailable - but this refers to the buffer, not the stream itself (as discussed here). I mention this only so you don't try to use it to see if the stream is closed, since that isn't what it means.

If you wrap your Stream in a StreamReader, then you can use Peek or EndOfStream to test for closure:

bool isEnd = reader.EndOfStream;

or:

int b = reader.Peek();
if(b < 0) {... was end ...}
Marc Gravell
Unfortunatelly, this did not solve my problem. I'm fine with exception handling right now. Cheers!