Generally, "using" is preferred approach for accessing and disposing of a filestream properly.
I often need to leave the file open (as below). Can the "using" structure be employed in this case?
public class logger
{
private StreamWriter sw;
public logger(string fileName)
{
sw = new StreamWriter(fileName, true);
}
public void LogString(string txt)
{
sw.WriteLine(txt);
sw.Flush();
}
public void Close()
{
sw.Close();
}
}
Yes, you make Logger
disposable and have it dispose of the stream in its dispose method.
// I make it sealed so you can use the "easier" dispose pattern, if it is not sealed
// you should create a `protected virtual void Dispose(bool disposing)` method.
public sealed class logger : IDisposable
{
private StreamWriter sw;
public logger(string fileName)
{
sw = new StreamWriter(fileName, true);
}
public void LogString(string txt)
{
sw.WriteLine(txt);
sw.Flush();
}
public void Close()
{
sw.Close();
}
public void Dispose()
{
if(sw != null)
sw.Dispose();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With