Checking to se if a file stream opened and using a streamreader

A

AMP

Hello,
I am trying to see if a FileStream Opened using an"if" clause:
FileStream infile = new FileStream("c:\\blink2.txt", FileMode.Open,
FileAccess.Read, FileShare.Read);

if (infile==0).....

but that doesnt work (they dont compare)
ALSO,
FileStream(......) is a constructor, but behaves like a Method. I'm a
little confused

PLUS,
more importantly,I'm trying to use a Streamreader with the FileStream:
TextReader tr = new StreamReader("infile");

Is this correct?Do I need both a FileStream AND a Streamreader?
Thanks,
Mike
 
S

Simon Tamman

There is no need to check if the filestream has opened correctly, if it does
not open correctly it will probably throw an exception.
However you could try the CanRead or CanWrite properties of the FileStream
if you like.

You can read data directly from a filestream but it only natively supports
bytes which usually isn't very useful.
This is why in most instances you use a StreamReader and pass a reference to
the FileStream as an argument. This object wraps the filestream and converts
the bytes into more useful output (like text).

A couple of additional pointers.

if( infile == 0 )

This comparison is not valid because you are trying to compare a FileStream
reference to an integer, in that instance I believe the following would be
more applicable.

if(infile.CanRead == true) - Or - if(infile.CanRead)
Or possibly a more accurate version would be
if(infile != null)

In the last version we check if infile is actually a valid reference.

Additionally it would appear that you passed the string literal "infile" to
the streamreader, you do need to pass in the reference so infile, but
without the quotes.

HTH

Simon
 

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