DataContractSerializer - how can I output the xml to a string (as opposed to a file)

后端 未结 5 1666
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 15:23

I had a quick question regarding the datacontractserializer. Maybe it\'s more of a stream question. I found a piece of code that writes the xml to a filestream. I basically don\

5条回答
  •  情歌与酒
    2021-01-31 16:04

    Something like this - put your output into a MemoryStream and then read that back in:

    public static string DataContractSerializeObject(T objectToSerialize)
    {
        using(MemoryStream memStm = new MemoryStream())
        {
            var serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(memStm, objectToSerialize);
    
            memStm.Seek(0, SeekOrigin.Begin);
    
            using(var streamReader = new StreamReader(memStm))
            {
                 string result = streamReader.ReadToEnd();
                 return result;
            }
        }
    }
    

提交回复
热议问题