Search code examples
c#streamreaderstreamwriterusing-statement

Multiple using statements with if condition


I need to read one file and write processed data into one or optionally two files.

How to organize the Using statements in this case? Will something like this work?

if (condition)
    using (var sw2 = StreamWriter(writeFile2))
using (var sr = new StreamReader(readFile))
using (var sw = StreamWriter(writeFile))
{
    var line = sr.ReadLine();
    sw.WriteLine(line);
    if (condition)
        sw2.WriteLine(line);
}

Solution

  • Using blocks can handle a null fine. You can then do something like:

    using (var sr = new StreamReader(readFile))
    using (var sw = StreamWriter(writeFile))
    using (var sw2 = condition ? new StreamReader(writeFile2) : null)
    {
        var line = sr.ReadLine();
        sw.WriteLine(line);
        sw2?.WriteLine(line);
    }
    

    Where I've moved the sw2 after the open stream reader so that the file won't get created if the opening of the read file fails, and used the "safe navigation operator" ?. to handle the case of sw2 being null in the loop.