The thing everyone trips up on the first time they try this (myself
included) is that streams have only one "current position". After you write
to the stream, your next read position is the spot in the stream AFTER WHAT
YOU JUST WROTE.
This explains the behavior easily - you were trying to read from a stream
where the current position was already at the end of the stream. The written
data was behind the read pointer.
The fix is simple: seek the stream back to the beginning before doing a
read. Here's a little test that demonstrates what you have to do (just drop
it into an NUnit test harness and it'll run even):
[TestFixture]
public class MemoryStreamFixture
{
[Test]
public void WriteAndReadMemoryStream()
{
MemoryStream memStream = new MemoryStream();
// Write some data into the stream. You need to
// call writer.Flush() before reading to make
// sure the data's actually in the stream, and
// not in the writer's buffer.
StreamWriter writer = new StreamWriter(memStream);
writer.WriteLine("Here is my string");
writer.Flush();
// Set up to read from the memory stream. We need a reader:
StreamReader reader = new StreamReader(memStream);
// But if we read immediately, we won't get anything!
string input = reader.ReadLine();
Assert.IsNull(input);
// So rewind the stream first:
memStream.Seek(0, SeekOrigin.Begin);
// Now we'll see the data.
input = reader.ReadLine();
Assert.AreEqual("Here is my string", input);
}
}
Hope this helps explain things,
-Chris
________________________________________
From: padnug@xxxxxxxxxxxxxxx [mailto:padnug@xxxxxxxxxxxxxxx] On Behalf Of
Luke Olsen
Sent: Wednesday, June 14, 2006 1:38 PM
To: padnug@xxxxxxxxxxxxxxx
Subject: RE: [padnug] Converting a MemoryStream to a String
Another idea?
See if this returns anything:
MemoryStreamObject.ToArray().ToString
-----Original Message-----
From: padnug@xxxxxxxxxxxxxxx [mailto:padnug@xxxxxxxxxxxxxxx] On Behalf Of
Keith R. Pinster
Sent: Wednesday, June 14, 2006 11:49 AM
To: padnug@xxxxxxxxxxxxxxx
Subject: [padnug] Converting a MemoryStream to a String
I've been banging my head against this for a couple of hours and just can't
figure it out. I've got an object that dumps it's result into a
MemoryStream object. Can someone tell me how to convert this to a string?
Thanks
KRP
------------------------ Yahoo! Groups Sponsor --------------------~-->
Home is just a click away. Make Yahoo! your home page now.
http://us.click.yahoo.com/DHchtC/3FxNAA/yQLSAA/dpFolB/TM
--------------------------------------------------------------------~->
|