Is there anyway to close a StreamWriter without closing it's BaseStream?

Posted by Binary Worrier on Stack Overflow See other posts from Stack Overflow or by Binary Worrier
Published on 2010-04-19T11:16:21Z Indexed on 2010/04/19 11:23 UTC
Read the original article Hit count: 347

Filed under:
|

My root problem is that when using calls Dispose on a StreamWriter, it also disposes the BaseStream (same problem with Close).

I have a workaround for this, but as you can see it involves copying the stream. Is there any way to do this without copying the stream?

The purpose of this is to get the contents of a string (originally read from a database) into a stream, so the stream can be read by a third party component.
NB I cannot change the third party component.

public System.IO.Stream CreateStream(string value)
{
    var baseStream = new System.IO.MemoryStream();
    var baseCopy = new System.IO.MemoryStream();
    using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8))
    {
        writer.Write(value);
        writer.Flush();
        baseStream.WriteTo(baseCopy); 
    }
    baseCopy.Seek(0, System.IO.SeekOrigin.Begin);
    return baseCopy;
}

Used as

public void Noddy()
{
    System.IO.Stream myStream = CreateStream("The contents of this string are unimportant");
    My3rdPartyComponent.ReadFromStream(myStream);
}

Ideally I'm looking for an imaginery method called BreakAssociationWithBaseStream, e.g.

public System.IO.Stream CreateStream_Alternate(string value)
{
    var baseStream = new System.IO.MemoryStream();
    using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8))
    {
        writer.Write(value);
        writer.Flush();
        writer.BreakAssociationWithBaseStream();
    }
    return baseStream;
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about stream