Home > DeveloperSection > Forums > assign textwriter to memory writer
Tanuj Kumar

Total Post:134

Posted on    September-02-2014 12:30 AM


 1 Reply(s)
 791  View(s)
Rate this:

I am writing xml file but missing some value for specific field. i check that when object comes which contains value that specific value exist but after writing xml value doesn't exist. following is the code which is using. I think XmlTextWriter could be the cause of wrong xml. There is another method which could be used for it that is TextWriter but failed to convert it into memorystream.

string xmlString = null;

            MemoryStream memoryStream = new MemoryStream();

            XmlSerializer xs = new XmlSerializer(typeof(T));

           // XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.ASCII);

            TextWriter xmlTextWriter=new StreamWriter(memoryStream,Encoding.ASCII);

            xs.Serialize(xmlTextWriter, obj);

            memoryStream =(MemoryStream)xmlTextWriter.   //(MemoryStream)xmlTextWriter.BaseStream;

            xmlString = ASCIIByteArrayToString(memoryStream.ToArray()); return `xmlString;`

Any idea how i can know why and where the problem occur.

Sumit Kesarwani

Total Post:378

Posted on    September-02-2014 12:47 AM

Hi Tanuj, 

Try disposing properly your IDisposable resources by wrapping them in using statements:

public string SerializeToXml<T>(T obj)


    using (var stream = new MemoryStream())


        var xs = new XmlSerializer(typeof(T));

        xs.Serialize(stream, obj);

        return Encoding.UTF8.GetString(stream.ToArray());



Don't want to miss updates? Please click the below button!

Follow MindStick