private static void Serialize1(string filename, object obj)
{
var stream = new FileStream(filename, FileMode.OpenOrCreate);
var serializer = new DataContractSerializer(typeof (PackageManifest));
serializer.WriteObject(stream, obj);
stream.Close();
}
当用以上方法,序列化一个对象后,用下面的反序列方法,发现有的文件居然不能反序列化,(PackageManifest 里面没有特殊对象,不然不会有的可以序列化,而有的不可以)
private PackageManifest Deserialize( string manifestFilePath)
{
try
{
var serializer = new DataContractSerializer(typeof (PackageManifest ));
var stream = new FileStream(manifestFilePath, FileMode.Open, FileAccess .Read);
var manifestObject = serializer.ReadObject(stream) as PackageManifest;
stream.Close();
return manifestObject;
}
catch ( Exception ex)
{
return null;
}
}
然而,当我用格式化工具,将Serialize1序列化的对象格式化后,再来调用反序列化居然又可以了。 于是找到一个办法,Serialize的时候直接输出格式化的xml就没有问题了。
private static void Serialize2(string filename, object obj)
{
var ds = new DataContractSerializer(typeof (PackageManifest ));
var settings = new XmlWriterSettings { Indent = true };
using ( var writer = XmlWriter.Create(filename, settings))
{
ds.WriteObject(writer, obj);
}
}