简体   繁体   English

在WP7的隔离存储中存储类对象

[英]Storing class object in Isolated Storage in WP7

How can I store object of a class in WP7 Isolated Storage? 如何在WP7隔离存储中存储类的对象? I want to retrieve it and edit it whenever required. 我想检索它并在需要时进行编辑。

You need to serialize your data to save it, then deserialize it to load it. 您需要序列化数据以保存它,然后反序列化以加载它。 You can find a complete worked example in this article . 您可以在本文中找到完整的可用示例。

For example, mark the class and properties as follows: 例如,将类和属性标记如下:

[DataContract] 
public class Employee  
{  
     [DataMember] 
     public int EmployeeNumber { get; set; }  
     [DataMember] 
     public string Name { get; set; }  
     [DataMember] 
     public string Department { get; set; }  
}

Construct a serializer: 构造一个序列化器:

DataContractSerializer mySerializer = new DataContractSerializer(typeof(Employee)); 

Then load / save via ReadObject / WriteObject . 然后通过ReadObject / WriteObject加载/保存。

U can use xml serialisation 你可以使用xml序列化

    public static void Serialize<T>(T obj, string fileName)
    {   
     try
      {
        var store = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Create);

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        using (XmlWriter xmlWriter = XmlWriter.Create(stream, writerSettings))
        {
            serializer.Serialize(xmlWriter, obj);
        }

    stream.Close();
   }
   catch (Exception ex)
   {
      throw ex;
   }
  }


    public static T DeSerialize<T>(string fileName)
    {
      try
      {
         var store = IsolatedStorageFile.GetUserStoreForApplication();
         IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Open);

         XmlSerializer serializer = new XmlSerializer(typeof(T));
         return (T)serializer.Deserialize(stream);
      }
      catch (Exception ex)
      {
        throw ex;
      }
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM