Search code examples
c#streamfilestreamstreamwriterflush

Can wrapping of base stream of another wrapper lead to data loss?


There is a code:

using (var sw1 = new StreamWriter(filename))
{
    var sw2 = new StreamWriter(sw1.base as FileStream);
    while (...)
       sw2.WriteLine(...); //a lot of lines are written
}

Can it lose some data without explicit flushing of sw2? According to MSDN (as I remember) internal stream should not be disposed directly, that's why I doesn't cover sw2 by using also.

Why do I need sw1? Cause it's just example and I have same situation in my project as a result of its architecture (sw1 is created out of a function with sw2 and should be passed as FileStream due to an interface).


Solution

  • Obviously, yes, it can. To prevent data losing sw2 should be flushed before writing to sw1 will be continued. Also sw2 should not be used after sw1 disposing.