views:

111

answers:

1

Given a method

    public static string[] Foo(System.IO.Stream stream)
    {
        XmlTextWriter xmlWriter = new XmlTextWriter(stream,   System.Text.Encoding.ASCII);

        xmlWriter.WriteStartDocument();
        xmlWriter.WriteStartElement("Element");
        xmlWriter.WriteEndElement();
        xmlWriter.WriteEndDocument();
        xmlWriter.Flush();

        return new string[3]{"1", "2", "3"};
    }

and a calling code

using(MemoryStream memStream = new MemoryStream())
{
     string[] playerIDs = PlayerCommand.Foo(stream);
     // do some stuff with stream and playerIDs
}

When the control passes out of the using directive, is there a problem that xmlWriter was not explicitly closed in Foo (which would make the stream useless)?

Also, is passing a Stream between methods unsavory, is there a better way to pass the results of XMLWriting back to the calling code (which will zip it up and file it away)?

Thanks in advance, Greg

+4  A: 

No problem here. A StreamWriter's Dispose() method basically first calls Flush() and then disposes the underlying stream, so as long as you have the Flush() covered yourself (which you do above) it's OK to leave it hanging as long as the stream's alive.

The other answers suggest disposing the Writer itself, but that's not really an option here, because it will dispose the underlying stream as well.

That said, if you're just putting an XML document in the stream and then using it later, I'd rather pass the XML document itself around instead of keeping track of the stream. But perhaps your code isn't as simple as all that.

mquander
Yes, good point.
Charlie Flowers
What other answers :) LOL
Charlie Flowers
I chose not pass the xmldocument around because I thought I had to save it before I could zip it with ICSharpCode.SharpZipLib.Zip. Perhaps this is wrong?
sympatric greg