Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use "using" but leave file open?

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();
    }
}
like image 722
ManInMoon Avatar asked Nov 05 '14 16:11

ManInMoon


1 Answers

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();
    }
}
like image 178
Scott Chamberlain Avatar answered Sep 26 '22 10:09

Scott Chamberlain