bot47
bot47

Reputation: 1524

Testing if NetworkStream is closed

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.

Upvotes: 2

Views: 1137

Answers (3)

Boklucius
Boklucius

Reputation: 1926

The NetworkStream will return EOF (Read will return 0 bytes) when the other side closes the socket.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064204

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

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422290

stream.CanRead

Upvotes: 0

Related Questions