Search code examples
c#filestreamusing

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();
    }
}

Solution

  • 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();
        }
    }