2016-03-02 41 views
-1

我有這個孤立的存儲幫助器,我需要使用它來保存和檢索我的通用應用程序中的數據。其實,我不知道從哪裏開始。我是否應該製作一個應用程序並將輔助類加入其中? 這裏是我的課,感謝advanvceWindows通用應用程序隔離存儲

using System.IO; 
//using System.IO.IsolatedStorage; 
using System.Runtime.Serialization.Json; 
using System.Text; 
public static class IsolatedStorageHelper 
{ 
    public static T GetObject<T>(string key) 


    { 
     var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; 





     if (localSettings.Values.ContainsKey(key)) 
     { 
      string serializedObject = localSettings.Values[key].ToString(); 
      return Deserialize<T>(serializedObject); 
     } 

     return default(T); 
    } 

    public static void SaveObject<T>(string key, T objectToSave) 
    { 
     var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; 
     string serializedObject = Serialize(objectToSave); 
     localSettings.Values[key] = serializedObject; 
    } 

    public static void DeleteObject(string key) 
    { 
     var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; 
     localSettings.Values.Remove(key); 
    } 

    private static string Serialize(object objectToSerialize) 
    { 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType()); 
      serializer.WriteObject(ms, objectToSerialize); 
      ms.Position = 0; 

      using (StreamReader reader = new StreamReader(ms)) 
      { 
       return reader.ReadToEnd(); 
      } 
     } 
    } 

    private static T Deserialize<T>(string jsonString) 
    { 
     using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) 
     { 
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); 
      return (T)serializer.ReadObject(ms); 
     } 
    } 
} 
+0

你可以編輯你的問題,並提供更多的信息,你遇到了什麼問題,你在找什麼? – Romasz

+0

是的,事實上,我需要創建一個應用程序,並在不重寫整個代碼的情況下爲我的實體'person'製作一個crud。因此,我需要使用上面提到的類'storage helper.cs'。現在我被卡住了,因爲我不知道如何使用它,並將其實施到我的項目中。我真的會使用這個類來開發一個UWP的例子。謝謝你的幫助 –

回答

0

使用靜態SaveObject方法,並提供了「人」的實體和關鍵。稍後使用GetObject進行檢索。

但我認爲在這種情況下,您應該使用數據庫sqlitesqlite net包來保存實體。

相關問題