Friday, March 16, 2012

Populating a Stream object with XML and then convert Stream into a String Options

I am trying to populate a Stream via an XML Serializer and then
convert that stream of xml into a string.

I have been able to successfully serialize an object into a physical
xml file written to my local disk. The XML file has content and looks
as I would expect, here is the code for that action:

TextWriter writer = new StreamWriter(@dotnet.itags.org."c:\test.xml");
serializer.Serialize(writer, oData);

When I try to to serialize my object to a stream of xml and then
convert to a string I get no content in the string. Both the
MemoryStream and StreamWriter object appear to have the correct byte
size after I populate them with the serialized data. Is there an
alternative way I should be doing this? Here is the code I'm using:

MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);

serializer.Serialize(sw, oData);

StreamReader sr = new StreamReader(ms);

string test = "";
test = sr.ReadToEnd(); //No content is populated, why?

Thank you,
Darren

dstahl:

MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);

serializer.Serialize(sw, oData);

StreamReader sr = new StreamReader(ms);

string test = "";
test = sr.ReadToEnd(); //No content is populated, why?

Thank you,
Darren

Hi Darren,

In your code, after you serialize your sw, you couldn't new it again, because that will create sw again.

Try to cancel that line : "StreamReader sr = new StreamReader(ms); ". As you know, if you do like your way, ms has nothing, then sw has nothing too, even if you have initialize the sw before.

Hope this helps. Thanks.

0 comments:

Post a Comment