Using memoryStream / Serialization

F

Fabiano

Please,

i have an object that i need to serialize into a XML String. i don't want to
do it using filestream. How can i do using MemoryStream?

i created the code below, but when i use the ToString() method i get just
the object name, not the real data.

RetornoInclusao objRet = new RetornoInclusao();
objRet = objAutenticacao.IncluirSistema(dsSistema);
XmlSerializer serializer = new XmlSerializer(typeof(RetornoInclusao));
MemoryStream writer = new MemoryStream();
serializer.Serialize(writer, objRet);
writer.Position = 0;
string tmpXML = writer.ToString();
writer.Close();

tks in adv.

Fabiano
 
N

Nicholas Paldino [.NET/C# MVP]

Fabiano,

The ToString method for the memory stream will not give you the contents
of the stream. Rather, what you have to do is call the ToArray method on
the MemoryStream instance to get an array of bytes that corresponds to the
stream. Once you have that, you can run the bytes through an encoder
(Unicode, Ascii, whatever you used to encode the stream), to get the
contents in a string.

Hope this helps.
 
H

Hugo Wetterberg

Try this approach instead, it's pretty easy. Always use try and
finally when you work with streams.

/Hugo

XmlSerializer serializer=new XmlSerializer(typeof(SerializeClass));
MemoryStream ms=new MemoryStream();
try
{
serializer.Serialize(ms,instance);

ms.Position=0;
StreamReader reader=new StreamReader(ms,true);
string tempXml=reader.ReadToEnd();

//Do something with the string
}
finally
{
ms.Close();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top