seralization as string

  • Thread starter Thread starter Alisa
  • Start date Start date
A

Alisa

How can i get the seralization of an object as string?
Can i avoid saving a temporary file?
thanks
 
Alisa,

Do you want to store it in a string variable, or do you just need a
string format?

What you could do is use serialization (not the XML serializer, but the
BinaryFormatter) and serialize to a MemoryStream. Then, you can take the
bytes from the memory stream and pass them to the static ToBase64String
method on the Convert class to get your string.

Hope this helps.
 
try the following

public static string SerializeObjectToString( object obj) {

// uses UTF8 encoding, in a more complicated situation this
would
// be configurable

System.Text.Encoding ENCODING = System.Text.Encoding.UTF8;

XmlSerializer ser = new XmlSerializer(obj.GetType());
MemoryStream mem = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mem,ENCODING);

ser.Serialize(writer,obj);

return ENCODING.GetString(mem.GetBuffer());

}


hth,
Alan.
 
Hello,
System.Text.Encoding ENCODING = System.Text.Encoding.UTF8;
XmlSerializer ser = new XmlSerializer(obj.GetType());
MemoryStream mem = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mem,ENCODING);
ser.Serialize(writer,obj);
return ENCODING.GetString(mem.GetBuffer());

In such string cases StringWriter is better. The MemoryStream
solution has drawbacks because some characters will
not be translated (and its more difficult). You can verify
this by serializing a DataSet. So:

XmlSerializer ser = new XmlSerializer(obj.GetType());
StringWriter sw = new StringWriter();
ser.Serialize(sw,obj); string ret= sw.ToString();


ciao Frank
 
Chris said:
You can use an xmlserializer to serialize to xml which can be stored
in a string.

Well strictly speaking you do not avoid an intermediate file because the
XmlSerializer class creates a dynamic assembly for the type that you are
serializing, and this assembly is temporarily stored somewhere in your
profile's folders. (I forget where, but I tracked it down once by
putting a FileSystemWatcher to monitor the profile's folders.)

The Formatter classes (binary and soap) serialize an object to a stream.
You can use a MemoryStream to collect this data. If you use the soap
formatter you can then use one of the Encoding classes to convert the
MemoryStream's buffer to text XML. If you use the binary formatter then
you can convert the binary data in the MemoryStream to base64, which is
a string, although not a human readale one ;-)

Even better, I have a base64 routine implemented as a stream class, so
you can simply pass an instance of that to the formatter.

Richard
 
Back
Top