在 Windows Phone (C#) 中将复杂对象作为 XML 文件保存到隔离存储
本文关键字:XML 文件 保存 存储 隔离 对象 复杂 Phone Windows | 更新日期: 2023-09-27 18:37:24
我正在使用此代码作为我的隔离存储助手。
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
的变量/属性的类。您无法序列化该类型,因此会得到上述异常。尝试通过序列化名称或类似的东西并在从该信息反序列化时实例化 BitmapImage 来解决。
如果你想在
iso 存储中保存一些不可序列化的东西,那么如果你编写自己的序列化方法,你仍然可以这样做。
大概BitmapImage不是您应用程序的原始部分,或者您已经拥有它的文件,所以我想它一定是新获得的位图。
将BitmapImage转换为字节数组,您应该没有问题。