[英]Saving complex object to IsolatedStorage as XML file in Windows Phone (C#)
我將此代碼用作我的IsolatedStorage助手。
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.
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
類型的變量/屬性的類。 您無法序列化該類型,因此會遇到上述異常。 嘗試通過序列化名稱或類似名稱並從該信息反序列化實例化BitmapImage來變通。
如果您想將某些內容保存在無法序列化的iso存儲中,那么如果您編寫自己的序列化方法,仍然可以這樣做。
大概BitmapImage不是您應用程序的原始部分,或者您已經有了該文件,因此我想它一定是新獲取的位圖。
將您的BitmapImage轉換為字節數組,應該沒有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.