Hello:
I have a memory stream that I am writing XML to. I have a declaration
like this:
MemoryStream memoryStream = new MemoryStream();
using (XmlWriter writer = new XmlTextWriter(new
StreamWriter(memoryStream)))
{
// do something
}
memoryStream.Seek(0, SeekOrigin.Begin); // this is where is fails
return new XmlTextReader(memoryStream);
I have checked the results and the XML is getting written to the
MemoryStream. The problem seems to be that when I leave the using
statement, either XmlTextWriter or the StreamWriter is closing my
MemoryStream.
How do I prevent the automatic close?
Thanks,
Travis
jehugaleahsa@gmail.com - 06 Feb 2008 16:49 GMT
On Feb 6, 9:34 am, "jehugalea...@gmail.com" <jehugalea...@gmail.com>
wrote:
> Hello:
>
[quoted text clipped - 19 lines]
> Thanks,
> Travis
The using statement was calling Dispose, I suppose and made my stream
close.
Thanks anyway,
Travis
Nicholas Paldino [.NET/C# MVP] - 06 Feb 2008 17:01 GMT
Travis,
I would just take note of the length of the MemoryStream and get the
buffer:
MemoryStream memoryStream = new MemoryStream();
// The length of the stream as well as the buffer.
long length = 0;
byte[] buffer = null;
using (StreamWriter streamWriter = new StreamWriter(memoryStream))
using (XmlWriter writer = new XmlTextWriter(streamWriter))
{
// do something
// Take note of the length. Do this because the Length property is not
accessible after
// the call to Dispose. Also get the buffer while at it.
length = memoryStream.Length;
buffer = memoryStream.GetBuffer();
}
// Create a new memory stream and pass the buffer.
memoryStream = new MemoryStream(buffer, 0, (int) length, true, true);
The buffer is just the backing store for the memory stream, you could
call ToArray, but it will create a copy of the array, and there is no reason
to do that if you can get all the information you need beforehand.

Signature
- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com
> Hello:
>
[quoted text clipped - 19 lines]
> Thanks,
> Travis
Marc Gravell - 06 Feb 2008 19:37 GMT
> when I leave the using
> statement, either XmlTextWriter or the StreamWriter is closing my
> MemoryStream.
>
> How do I prevent the automatic close?
The XmlWriterSettings offers this as an option:
XmlWriterSettings settings = new XmlWriterSettings();
settings.CloseOutput = false;
using (XmlWriter writer = XmlWriter.Create(memoryStream,
settings))
{
// etc
}
Some wrappers don't offer this option; in which case, Jon Skeet has a
NonClosingStreamWrapper (link below) that also does exactly what you
want. Of course, in the case of a memory-stream you can cheat in a few
ways, but this isn't always an option...
http://www.pobox.com/~skeet/csharp/miscutil/
It doesn't mention it on the page, but it is there ;-p
(Jon: you might want to update that if you update that page any time
soon [cough])
Marc