[Mono-list] Re: Serializing Objects to a Stream

Robert Jordan robertj at gmx.net
Fri Aug 26 06:58:29 EDT 2005


Jonathan,

> how can i serialize an object to Xml but storing the object to a
> Stream and not to a File?

A file _is_ a stream. Where is the point? Do you mean storing to memory?
Then use MemoryStream.

> I am looking for a way to do XmlSerialization (or maybe
> SoapSerialization) to send objects

Maybe? XmlSerialization and Binary+SoapSerialization are
totally different, so you should take a decision soon:

- XmlSerialization is mainly used for WebServices, because it
   assures cross-platform compatibility. It can only be used
   with custom types (types you have defined) and some basic
   types.

   See 
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconintroducingxmlserialization.asp

- Binary+SoapSerialization is .NET-only

> via Remoting over the wire, and the deserialize on the Server the
> serialized object stream.
> how to?
> 
> This may sound strange, but that's they way i should do it.

Since streams cannot be remoted you have to convert the
stream to a byte[] or to a string:

         // using binary serialization
         public static byte[] SerializeToArray(object data)
         {
             MemoryStream stream = new MemoryStream();
             BinaryFormatter formatter = new BinaryFormatter();
             formatter.Serialize(stream, data);
             return stream.ToArray();
         }

         // using XML serialization
         public static string XmlSerializeToString(object data)
         {
             StringBuilder b = new StringBuilder();
             XmlSerializer x = new XmlSerializer(data.GetType());
             TextWriter w = new StringWriter(b);
             x.Serialize(w, data);
             w.Close();
             return b.ToString();
         }

The deserialization methods are left as an exercise for the reader ;-)

Rob



More information about the Mono-list mailing list