0
public static async Task SaveFileAsync(string FileName, T data)
{
    MemoryStream memStream = new MemoryStream();
    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
    serializer.WriteObject(memStream, data);

    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(FileName,
        CreationCollisionOption.ReplaceExisting);
    using (Stream stream = await file.OpenStreamForWriteAsync())
    {
        memStream.Seek(0, SeekOrigin.Begin);
        await memStream.CopyToAsync(stream);
        await stream.FlushAsync();
    }
}

public static async Task<T> RestoreFileAsync(string FileName)
{
    T result = default(T);
    try
    {
        StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(FileName);
        using (IInputStream inStream = await file.OpenSequentialReadAsync())
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            result = (T)serializer.ReadObject(inStream.AsStreamForRead());
            return result;
        }
    }

    catch (FileNotFoundException)
    {
        return default(T);
    }
}

我正在使用这些方法来序列化我的数据,但我有一个包含图像的类,

[DataMember]
Public Image img{get;set;}

我正在尝试序列化它。我实际上正在执行以下操作

var thumb = await item.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView,
                        1000, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);

BitmapImage bmg = new BitmapImage();
bmg.SetSource(thumb);
Image img = new Image();
img.Source = bmg;

我试图序列化它自己的bitmapImage,但这是同样的问题。我不断收到此错误,并且我的 BitmapImage 有一个属性。

无法序列化类型“Windows.UI.Xaml.Media.ImageSource”。考虑使用 DataContractAttribute 属性对其进行标记,并使用 DataMemberAttribute 属性标记您想要序列化的所有成员。如果该类型是一个集合,请考虑使用 CollectionDataContractAttribute 对其进行标记。有关其他支持的类型,请参阅 Microsoft .NET Framework 文档。

4

1 回答 1

0

DataContractSerializer不适用于图像。您应该使用BitmapEncoder(如果您正在处理WriteableBitmap或只是序列化您的BitmapImage.BitmapImage无论如何,因此您需要从原始源 URL 下载源文件或复制您加载的本地文件。然后您可以将该副本保存为松散文件或序列化为 Base64 在您创建的DataContractSerializerXML 中。

于 2013-02-21T08:37:59.357 回答