katit
katit

Reputation: 17915

System.ObjectDisposedException. What is the proper way to handle stream writer?

Here is my code, self-explanatory. After using block terminates - output variable being disposed. Why? I want to return it from function, what is the proper way to dispose StreamWriter but return my object?

public static Stream Write(Interchange interchange)
{
    var output = new MemoryStream();
    using (TextWriter writer = new StreamWriter(output))
    {
        foreach (var rawSegment in GetRawSegments(interchange))
        {
            writer.Write(rawSegment.ToString(interchange.ElementDelimeter, interchange.SegmentTerminator));
        }

        writer.Flush();
     }

     return output;
}

Upvotes: 2

Views: 3464

Answers (3)

John C
John C

Reputation: 21

Inside the loop, create new instance, when it's necessary...

using (StreamWriter writer = new StreamWriter(@"C:\Users\\Documents\Dev\error.txt", true))
{
    writer.WriteLine("cod: " + codERP );
}

Steamwriter automaticaly close file.

try get all information you need (inside for) after write in your file(once time)

Upvotes: 0

alexm
alexm

Reputation: 6882

StreamWriter does not have unmanaged resources besides the stream to dispose of. Calling TextWriter.Dispose() results in closing the underlying stream. To keep the stream open remove using block:

var output = new MemoryStream();
TextWriter writer = new StreamWriter(output);
foreach (var rawSegment in GetRawSegments(interchange))
{
   writer.Write(rawSegment.ToString(interchange.ElementDelimeter, interchange.SegmentTerminator));
}

writer.Flush();

return output;

PS: For .NET 4.5 and above Reed's answer looks more elegant.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564441

There is a constructor for StreamWriter which allows you to specify, via a bool, to not close the underlying Stream:

using (TextWriter writer = new StreamWriter(output, Encoding.UTF8, 1024, true))
{

Note that you may also want to reset the position of the MemoryStream to zero before returning it, depending on how it'll be used.

Upvotes: 3

Related Questions