How can I tell if a streamwriter is closed?

Melanie picture Melanie · Jul 4, 2012 · Viewed 9.9k times · Source

I'm using a streamwriter in combination with a background worker, for logging.

As such, I have

System::Void
MyUI::execBWorker_DoWork(System::Object^  sender, System::ComponentModel::DoWorkEventArgs^  e) {

String^ outputPath = _clr::Settings::ApplicationLogPath("_log.txt", true, false);
logfile_ = gcnew StreamWriter(outputPath,true);

DoStuff();
logfile_->Close();
}

Things in the DoStuff() method raise the Progress event.

System::Void
MyUI::execBWorker_ProgressChanged(System::Object^  sender, System::ComponentModel::ProgressChangedEventArgs^  e) {
logfile_->WriteLine("something");
}

I think this really smells. How can I make it better, or at least how can I check the logfile hasn't been closed? There are a lot of messages, so I'm concerned about opening and closing the logfile continuously.

Answer

leppie picture leppie · Jul 4, 2012

If the StreamWriter is closed, the BaseStream property will return null.