XmlWriter.Create不在流中创建对象

时间:2012-03-16 13:55:25

标签: c# serialization

System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
XmlWriter xdw = XmlWriter.Create(ms);
ser.WriteObject(xdw, obj);

ms的长度为0

为什么?

1 个答案:

答案 0 :(得分:1)

有效:

class Program
{
    static void Main(string[] args)
    {
        var obj = "bugaga!";
        System.Runtime.Serialization.DataContractSerializer ser = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
        MemoryStream ms = new MemoryStream();
        using (XmlWriter xdw = XmlWriter.Create(ms))
        {
            ser.WriteObject(xdw, obj);
        }
        Console.WriteLine(ms.Length);
    }
}

[更新] 或者只是做xdw.Flush(),已经注意到了