3

I'm writing a class that exports data to a CSV file, and its constructor takes in a TextWriter. The reason I'm using a TextWriter rather than a StreamWriter is so that it would make testing easier: I can use the same constructor for writing to a StreamWriter (which writes to files, the intended use-case) and to write to a StringWriter (which is useful for testing).

In my constructor I would like to perform some validation on the passed in TextWriter. The problem is I can't seem to figure out how to check if the TextWriter is open or closed. It's possible for StreamWriter if the BaseStream property is null. TextWriter does not have this property however. Is there another way of checking if a TextWriter is open or not?

9a3eedi
  • 696
  • 2
  • 7
  • 18
  • 1
    I don't think you can do that without hacking into private fields, but I also don't think it really matters. Fail on access is not a very bad situation for your case because in common scenario your class will be used to write immediately after initialisation. – tia Mar 17 '15 at 06:11
  • The class I'm writing will not write immediately after initialization. The class has a thread that will run in the background and keep writing over a period of time until it is told to stop. – 9a3eedi Mar 17 '15 at 10:04

1 Answers1

0

You may try like this:

if( writer.BaseStream != null)
{
   writer.WriteLine("Writer is open");
}
else
{
   MessageBox.Show ("Writer is closed");
}

i.e, if the BaseStream is NULL, then writer is already disposed.

Also it is recommended to use the using block for this as it takes care of this.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • The problem is that TextWriter does not have a BaseStream property, which is why I'm asking this question. – 9a3eedi Mar 17 '15 at 09:58
  • 1
    @9a3eedi:- Indeed. So I guess then the only way left is to use the `using` block as it will dispose everything once its completed. – Rahul Tripathi Mar 17 '15 at 10:01
  • The 'using' block suggested above is not very tenable when you have long-running and a large amount of code. To dispose of the type directly, call its Dispose method in a try/catch block. – Su Llewellyn Apr 23 '19 at 16:44