2012-11-15 102 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的參數。