determining the status of a stream

L

Lee Crabtree

Is there some way to find out if a stream is already open? In
particular, I want to be able to switch from a NetworkStream to a
FileStream depending on input. I know I can use a Stream object and
cast it up, but how do I find out if the stream has been closed?

The pseudocode would go a little something like this:

public void OpenNetConnection(Socket connection)
{
if the stream is closed
open a new NetworkStream based on the connection Socket.
else
throw an exception
}

public void OpenFileConnection(string filename)
{
if the stream is closed
open a FileStream to the file
else
throw an exception
}

Lee Crabtree
 
D

Derrick Coetzee [MSFT]

Lee said:
Is there some way to find out if a stream is already open? In
particular, I want to be able to switch from a NetworkStream to a
FileStream depending on input. [...]

public void OpenNetConnection(Socket connection) {
if the stream is closed
open a new NetworkStream based on the connection Socket.
else
throw an exception
}

public void OpenFileConnection(string filename) {
if the stream is closed
open a FileStream to the file
else
throw an exception
}

Hi Lee. The short answer is, no, there is no method or property on the
abstract Stream class supporting this query. The simplest solution is to set
your Stream reference to null when you close it - then later you can test it
against null to see if it's closed. By restructuring your methods you may
also be able to statically ensure the property that the stream is closed
when the new stream is opened, so that an exception is not necessary; for
example, you might only have an operation which closes the existing stream
and opens a new stream. Note that while it's possible to have a single
Stream reference refer to multiple kinds of streams over its lifetime, each
of these must be represented by a different runtime object. I hope this
helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top