在 IsolatedStorage中存取 Serialized Data (ver xml)

在 IsolatedStorage中存取 Serialized Data (ver xml)

在coding時,我們很常遇到,將物件直接儲存起來,需要的時候讀進來就可以馬上使用,不需要在重新設定屬性

感謝 IsolatedStorage ,讓我們可以用這種方式,將物件儲存起來,需要使用時候可以讀進來就可以使用了

基本上做法

(1) 儲存物件:  跟存取檔案系統一樣,但需要儲存物件序列化後的資料

(2) 讀取物件:  同上,但要將序列化後的資料 經過 反序列化的程序

需要使用 序列化工具 XmlSerializer

namespace System.Xml.Serialization

加入參考 “System.Xml.Serialization.dll”

IsolatedStorageFile

namespace System.IO.IsolatedStorage

片段程式

材料:

   1:  public class CustomerModel : INotifyPropertyChanged
   2:        {
   3:          public string CustFirstName { get; set; }
   4:   
   5:           public string CustLastName {get; set; }
   6:   
   7:            ....................
   8:   
   9:            public event PropertyChangedEventHandler PropertyChanged;
  10:   
  11:             private void RaisePropertyChanged(string propertyName)
  12:             {
  13:                 if (PropertyChanged != null)
  14:                 {
  15:                      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  16:                   }
  17:              }
  18:        }

儲存物件:

   1:  public void SaveItemToSerialize(CustomerModel item)
   2:              {
   3:                    if (item == null)  return;
   4:   
   5:                    try
   6:                    {
   7:                          using (var serstore = IsolatedStorageFile.GetUserStoreForApplication())
   8:                          using (var serstream = serstore.CreateFile("customer.xml"))
   9:                          using (var serwriter = new StreamWriter(serstream))
  10:                          {
  11:                                XmlSerializer ser = new XmlSerializer(typeof(CustomerModel));
  12:                                ser.Serialize(serwriter, item);
  13:                                writer.Close();
  14:                          }
  15:                    }
  16:                    catch (InvalidOperationException)
  17:                    {
  18:                          Message.Show("Save Fail");
  19:                    }
  20:              }

讀取物件:

   1:      try
   2:       {
   3:           CustomerModel DeserializeCustomerModel=null;
   4:            using (var serstore = IsolatedStorageFile.GetUserStoreForApplication())
   5:            if (serstore.FileExists("customer.xml"))
   6:            {
   7:                 using (var serstream = serstore.OpenFile("customer.xml", FileMode.Open))
   8:                 {
   9:                       XmlSerializer ser = new XmlSerializer(typeof(CustomerModel));
  10:                       DeserializeCustomerModel = ser.Deserialize(serstream) as CustomerModel;
  11:                       stream.Close();
  12:                    }
  13:               }
  14:               callback(...);
  15:      
  16:      } catch (InvalidOperationException ex)
  17:      {
  18:                callback(...);
  19:       }