0

Stream Writer creates a file even if there is nothing to write if Stream Writer was used in using statement, the Reason is using block calls dispose method at the end of block.

Code is

using (StreamWriter sw = new StreamWriter(@"d:\abc.txt"))
{

}

I wan't Not to create the blank file if there is nothing to write. The reason I am looking for is We are writing logs conditionally.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 5
    Use an `if` before to figure out if there is something to write? – nvoigt Jun 05 '15 at 10:45
  • @nvoigt Not always it is possible. If you are logging something, how can you know if you'll have something to log before logging it? Perhaps you only log errors, or warnings, not "normal" operations... Or perhaps you only log external events. – xanatos Jun 05 '15 at 10:54
  • 1
    @xanatos Considering you have the very same `if (something)` condition in your proposed solution, I don't really understand your comment. – nvoigt Jun 05 '15 at 10:58
  • @nvoigt The `if (something)` can be anything, and it represent the fact that there is no "automatic" writing inside the `using`. It could be `if (Console.ReadLine() == "YES")` – xanatos Jun 05 '15 at 11:00

1 Answers1

6

You could write something like:

Lazy<StreamWriter> sw = new Lazy<StreamWriter>(() => new StreamWriter(@"d:\abc.txt"));

try
{
    if (something)
    {
        sw.Value.WriteLine("Foo");
    }
}
finally
{
    if (sw.IsValueCreated)
    {
        sw.Value.Dispose();
    }
}

using Lazy<T> to encapsulate the StreamWriter.

You could even encapsulate Lazy<T> to "handle" IDisposable:

public sealed class DisposableLazy<T> : Lazy<T>, IDisposable where T : IDisposable
{
    public DisposableLazy(Func<T> valueFactory) : base(valueFactory)
    {
    }

    // No unmanaged resources in this class, and it is sealed.
    // No finalizer needed. See http://stackoverflow.com/a/3882819/613130
    public void Dispose()
    {
        if (IsValueCreated)
        {
            Value.Dispose();
        }
    }
}

and then

using (DisposableLazy<StreamWriter> sw = new DisposableLazy<StreamWriter>(() => new StreamWriter(@"d:\abc.txt")))
{
    if (something)
    {
        sw.Value.WriteLine("Foo");
    }
}
xanatos
  • 109,618
  • 12
  • 197
  • 280