使用DataContractSerializer在Isolatedstorage中存储数据

时间:2014-03-11 07:29:10

标签: c# windows-phone-7 windows-phone-8 isolatedstorage datacontractserializer

我正在使用带有Image&的ListBox的Windows Phone应用程序。文本块。此处图片位于应用程序的IsolatedStorage中。要在ListBlock中显示图像,我正在转换为流。在此之后我使用DataContractSerializer来序列化&存储在Isolatedstorage。

第1页的代码:

public BookDataList listobj = new BookDataList();

public class BookDataList : List<BookData>//for storing BookData class items with type of list
{
}  

    [DataContract]
public class BookData
{
    [DataMember]
    public BitmapImage ImageBinary
    {
        get { return m_ImageBinary; }
        set { m_ImageBinary = value; }
    }

    [DataMember]
    public BitmapImage m_ImageBinary;

    public BookData(string strImageName)
    {
        //*** Image Binary ***'
        BitmapImage image = new BitmapImage();
        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        string isoFilename = strImageName;
        Stream stream = isoStore.OpenFile(isoFilename, System.IO.FileMode.Open);
        image.SetSource(stream);
        this.ImageBinary = image;
        stream.Close();
    }

    [DataMember]
    public string BookName { get; set; }

    [DataMember]
    public string BookPath { get; set; }

    [DataMember]
    public string FolderPath { get; set; }
}

这里我要添加列表数据类型的项目:

            listobj.Add(new BookData(CoverImageForLib) { BookName = MyTitle.Value,  
BookPath = item.Path, FolderPath = split[1] });

这里我将存储到隔离存储中的文件:

  if (Settings1.FileExists("MyStoreItems"))
  {
      Settings1.DeleteFile("MyStoreItems");
  }
  using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Create))
  {
      DataContractSerializer serializer = new DataContractSerializer(typeof(BookDataList));
      serializer.WriteObject(fileStream, listobj);
  }
  NavigationService.Navigate(new Uri("/Library.xaml", UriKind.Relative));

这里我只是存储值。我将从我的文件/Library.xaml

中反序列化MyStoreItems中的值

修改:

我从here

获得了相关内容
  
      
  1. 您的“BookData”类没有公共无参数构造函数。这将在尝试重新加载时导致错误   数据

  2.   
  3. BitmapImage类不可序列化。

  4.         

    为了解决这两个问题,你需要编写   自定义序列化代码,您可以通过添加界面来执行此操作:   “IXmlSerializable”到你的班级并实现GetSchema,   ReadXml和WriteXml方法。

我在序列化System.Reflection.TargetInvocationException时遇到listobj异常。

如果代码令人困惑,请向我提问,以便我澄清。

修改1:

[DataContract]
public class BookData
{
    [DataMember]
    public string BookName { get; set; }
    [DataMember]
    public string Creator { get; set; }
    [DataMember]
    public string BookPath { get; set; }
    [DataMember]
    public string BookCoverPath { get; set; }
    [DataMember]
    public string FolderPath { get; set; }
    [DataMember]
    public BitmapImage Image { get; set; }
}

public class BookDataList : List<BookData>//for storing BookData class items with type of list
{

}  

我序列化&amp;将BookCoverPath存储为字符串。但每当我试图反序列化时,它都会给出异常。我对DataContractSerializer不熟悉。你能不能看看我做错了什么。

 // Here I getting data from file in Isolated storage
    if (Settings1.FileExists("MyStoreItems"))
        {
            using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Open))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(BookData));
                listobj1 = (BookDataList)serializer.ReadObject(fileStream);
            }
        }
    foreach (var item in listobj1)
    {
        string imagePath = item.BookCoverPath;
        item.Image = BookData(imagePath);
    }
    ListBox.ItemsSource = listobj1;//binding isolated storage list data

    public BitmapImage BookData(string imagePath)
    {
        //*** Image Binary ***'
        BitmapImage image = new BitmapImage();
        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        string isoFilename = imagePath;
        Stream stream = isoStore.OpenFile(isoFilename, System.IO.FileMode.Open);
        image.SetSource(stream);
        stream.Close();

        return image;
    }

1 个答案:

答案 0 :(得分:0)

BookData类已实现加载BitmapImage的逻辑。如果要在XML中持久化/序列化类,请删除此代码以获取simple DTO。这不会给您排序和保存带来任何麻烦。仅序列化imageName。您根本不需要自定义XML序列化程序。

要获取位图,请在反序列化xml后加载位图。你可以通过url加载图像,使用imageName来解析视图中的位图。 或者创建BookData的位图属性(但标记为[IgnoreDataMember])。反序列化元素后,在第二步中从isolatedStorage加载Bitmap,并在BookData上设置Bitmap。

[DataContract]
public class BookData
{
    [DataMember]
    public string BookCoverPath { get; set; }

    [IgnoreDataMember]
    public BitmapImage Image { get; set; }
}


public BookDataList LoadList()
{
  var booklist = loadAndDeserializeFromXML();
  return booklist == null 
    ? null 
    : this.WithBitmaps(booklist );
}

private BookDataList WithBitmaps(BookDataList bookData)
{
  bookData.BookData.ForEach(b =>
  {
    b.Image= loadPicture(b.BookCoverPath );
  });               
  return bookData;
}

由于抽象和测试,我会建议您在存储库类中实现loadAndDeserializeFromXML()loadPicture(string path)。不是ViewModel / CodeBehind本身。