如何从内存流中读回XML数据

时间:2015-11-22 08:37:21

标签: c# xml

我想将一个对象(使用XmlDictionaryWriter)写入内存流并将其读回。我有以下代码。当我从Memory Stream中读回对象时,它会崩溃。崩溃消息是:附加信息:反序列化Obj_4_1_Perform_IO_Operations.FullName类型的对象时出错。根级别的数据无效。第1行,第1位。

[DataContract]
public class FullName
{
    [DataMember]
    public string FirstName { get; set; }              
    [DataMember]
    public string LastName { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        FullName fn = new FullName();
        fn.LastName = "John";
        fn.LastName = "Doe";
        MemoryStream ms = Process(fn);
        Console.WriteLine("Read Back");
        ms.Position = 0;
        DataContractSerializer serializer = new DataContractSerializer(typeof(FullName));
        FullName fn2 = (FullName)serializer.ReadObject(ms); //<--- crash here      
        Console.WriteLine("Deserialized record: {0} {1}", fn2.FirstName, fn2.LastName);
    }
    public static MemoryStream Process(FullName name)
    {
        var ms = new MemoryStream();
        var binary = XmlDictionaryWriter.CreateBinaryWriter(ms);
        var ser = new DataContractSerializer(typeof(FullName));
        ser.WriteObject(binary, name);
        binary.Flush();
        Console.WriteLine("MemoryStream is {0} bytes long", ms.Length);
        return ms;
    }
}

0 个答案:

没有答案