2012-06-17 49 views
0

將此代碼用作IsolatedStorage Helper。將複雜對象保存爲Windows Phone中的XML文件(C#)

public class IsolatedStorageHelper 
{ 
    public const string MyObjectFile = "History.xml"; 
    public static void WriteToXml<T>(T data, string path) 
    { 
     // Write to the Isolated Storage 
     var xmlWriterSettings = new XmlWriterSettings { Indent = true }; 
     try 
     { 
      using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) 
      { 
       using (var stream = myIsolatedStorage.OpenFile(path, FileMode.Create)) 
       { 
        var serializer = new XmlSerializer(typeof(T)); 
        using (var xmlWriter = XmlWriter.Create(stream, xmlWriterSettings)) 
        { 
         serializer.Serialize(xmlWriter, data); //This line generates the exception 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      System.Diagnostics.Debug.WriteLine(ex.StackTrace); 
      //Dispatcher.BeginInvoke(() => MessageBox.Show(ex.StackTrace)); 
      //MessageBox.Show(ex.StackTrace); 
     } 
    } 
    public static T ReadFromXml<T>(string path) 
    { 
     T data = default(T); 
     try 
     { 
      using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) 
      { 
       using (var stream = myIsolatedStorage.OpenFile(path, FileMode.CreateNew)) 
       { 
        var serializer = new XmlSerializer(typeof(T)); 
        data = (T)serializer.Deserialize(stream); 
       } 
      } 
     } 
     catch 
     { 
      return default(T); 
      //add some code here 
     } 
     return data; 
    } 
} 

我救了我的班PdfFile,它具有的ImageSource作爲其屬性之一的對象。 但保存對象時產生異常,它聲明System.InvalidOperationException: The type System.Windows.Media.Imaging.BitmapImage was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. 我想知道這意味着什麼,以及如何解決這個問題。 謝謝

回答

1

您試圖序列化一個包含類型爲BitmapImage的變量/屬性的類。你不能序列化這種類型,所以你會得到上述例外。試着通過序列化一個名字或類似的東西來解決這個問題,並從該信息實例化反序列化的BitmapImage。

+0

可以將BitmapImage存儲爲IsolatedStorageSetting? –

+0

你可以試試。舉http://msdn.microsoft.com/en-us/library/gg680266(v=pandp.11).aspx:「和非序列化對象」 – Sascha

0

如果您想要保存ISO存儲的東西是不可序列化,那麼你仍然可以做,如果你寫你自己的序列化方法。

想必BitmapImage的是不是你的應用程序的原件或你已有的文件,所以我想這一定是一個新收購的位圖。

將您的BitmapImage轉換爲一個字節數組,你應該沒有問題。