assign textwriter to memory writer

Total Post:134


 1566  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.

  1. Re: assign textwriter to memory writer

    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());




Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.