將此代碼用作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.
我想知道這意味着什麼,以及如何解決這個問題。 謝謝
可以將BitmapImage存儲爲IsolatedStorageSetting? –
你可以試試。舉http://msdn.microsoft.com/en-us/library/gg680266(v=pandp.11).aspx:「和非序列化對象」 – Sascha