2012-11-15 101 views
0

我正在一个WPF应用程序中保存我的WPF应用程序退出时的对象列表。并获得系统启动时的对象列表。一切工作正常。但有时它会给出序列化异常。在得到异常后,我查看了xml序列化文件。但是在我看来,由于xml文件没有正确地形成而引发异常。当我纠正它。它再次运作良好。对象列表序列化xml错误

public static class IsolatedStorageCacheManager<T> 
{ 
    public static void store(T loc) 
    { 
     IsolatedStorageFile appStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null); 
     using(IsolatedStorageFileStream fileStream=appStore.OpenFile("myFile21.xml",FileMode.OpenOrCreate)) 
     { 
      DataContractSerializer serializer = new DataContractSerializer(typeof(T)); 
      serializer.WriteObject(fileStream, loc); 
     } 
    } 
    public static T retrieve() 
    { 
     T obj = default(T); 
     IsolatedStorageFile appStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null); 
     if (appStore.FileExists("myFile21.xml")) 
     { 
      using (IsolatedStorageFileStream fileStream = appStore.OpenFile("myFile21.xml", FileMode.Open)) 
      { 
       DataContractSerializer serializer = new DataContractSerializer(typeof(T)); 
       try 
       { 
        obj = (T)serializer.ReadObject(fileStream); 
       } 
       catch (SerializationException e) 
       { 
        Console.WriteLine(e.StackTrace); 
       } 
      } 
     } 
     return obj; 
    } 
} 
+1

是否有可能传入的一个或多个对象不可序列化? – CodingGorilla

+0

XML文件没有正确形成是什么意思?你如何纠正它,使其工作? –

回答

0

做的第一件事是确保传递给store的对象是一种supported by the DataContractSerializer的。

最简单的方法是自己检查所有store调用。

你也可以创建一个验证方法,甚至更好,看看其他人是否已经实现了一个。该方法可以验证loc对象并返回boolean,并在System.Diagnostics.Debug.Assert调用中在store方法的开始处被调用,以便它只能在调试配置上运行。但请注意,此方法可能非常棘手,因为您必须验证DataContractSerializer规范中提及的所有情况下的类型T,以及T是否也是通用验证T的参数。