Serialize object to XML and put it in memory stream RRS feed

  • Question


    Hello ,


      please look at this sample which seralize object to xml :


    static MemoryStream SerializeToXML(Movie movie)


    XmlSerializer serializer = new XmlSerializer(typeof(Movie));

    MemoryStream memoryStream = new MemoryStream();

    serializer.Serialize(memoryStream, movie);

    return memoryStream;



    static Movie CreateObject()


           // Movie is a class which contains three properties ( Title , ReleaseDate , Rating

    Movie movie1 = new Movie();

    movie1.Title = "Starship Troopers";

    movie1.ReleaseDate = DateTime.Parse("11/7/1997");

    movie1.Rating = 6;

    return movie1;



    static void Main(string[] args)


    Movie movie= CreateObject();

    MemoryStream stream = SerializeToXML(movie);

    byte[] array = new byte[stream.Length];

    stream.Read(array, 0, (int)stream.Length);

    string xmlData = System.Text.Encoding.ASCII.GetString(array);




    When I run the application , the Result was  " xmlData  "    is Empty .


     So what is wrong in my code ???????





    Sunday, July 27, 2008 3:02 PM


  • If you want to serialize to a string then use a StringWriter or StringBuilder, forget about the MemoryStream, that is not needed to get a string:

    Code Snippet

    StringWriter writer = new StringWriter();

    serializer.Serialize(writer, movie);


    string xmlData = writer.ToString();



    If you really think you need to use a MemoryStream then you need to reposition the stream after writing (serializing) to it so do stream.Position = 0; before you try to read from the stream. And also note that using ASCII encoding to decode the byte array is not a good idea if you use XML as XML is based on and uses Unicode so using ASCII might result in data loss. But all that code with the MemoryStream and byte array and GetString is not necessary if you want a string, a StringWriter is sufficient in that case.

    Sunday, July 27, 2008 4:37 PM