Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a StreamReader is still open?

Tags:

c#

I try to "wrap" a StreamReader in a class Fichier, with some extra methods and attributes.

I want two things :

  • The StreamReader opens automatically in the Fichier class;
  • The StreamReader opens when we use the overrided method ReadLine, and not before (we need to modify the file before reading it with a StreamReader).

A piece of my code looks like this :

public string ReadLine()
{
    if (Reader == null || ???)
    {
        Reader = new StreamReader(Path);
    }
    return Reader.ReadLine();
}

At ???, I want to check if the StreamReader has been closed. Indeed, if we do :

StreamReader sr = new StreamReader(path);
sr.Close();

sr is not null, but how to check that it is closed, and how to re-open it ?

If you wonder why I need to open and close StreamReader, it is because the Fichier object needs to exist anytime, but the file that it represents needs to be modified several times in an external program.

like image 818
Chostakovitch Avatar asked Apr 20 '15 14:04

Chostakovitch


1 Answers

The easiest thing is to Dispose (you really should do that, it closes the stream too) it and set it to null when you close it.

Optionally you could check for EndOfStream, but that requires you to read to the end of the stream.

like image 189
Patrick Hofman Avatar answered Sep 30 '22 15:09

Patrick Hofman