2015-04-21 74 views
1

我有一個ObservableCollection <T>。我想在其中插入各種元素,然後將新創建的文件保存在LocalStorage中。我怎樣才能做到這一點?如何在LocalStorage中保存文件?

SQLiteAsyncConnection conn = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Database.db"), true); 
await conn.CreateTableAsync<Musei>(); 
var Dbase = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Database.db"); 
var con = new SQLiteAsyncConnection(Dbase, true); 

var query = await con.Table<Musei>().ToListAsync(); 
ObservableCollection<Musei> favMusei = new ObservableCollection<Musei>(); 

if (query.Count > 0) 
{ 
    favMusei.Clear(); 

    foreach (Musei museifav in query) 
    { 
     favMusei.Add(museifav);    
    } 
} 
+0

當您運行現有代碼時,您會遇到什麼問題和/或問題..請提供更多信息 – MethodMan

+0

我想在本地存儲 – G111

+0

中保存'favmusei',這很不錯..但是在運行現有代碼時您遇到什麼問題代碼..不只是說'我想在本地存儲器中保存favmusei'調試代碼並告訴我們在哪裏發生故障.. – MethodMan

回答

0

我正在使用json文件存儲在內存中。 JSON是一種輕量級的消息交換格式,並且被廣泛使用。如果你想要一些不同的文件格式,你必須在代碼中做一些細微的修改。

您的集合將在保存時序列化到內存,並且在從內存中讀取時必須進行反序列化。

添加您自己的通用集合實現。要創建你的情況,我使用簡單的ObservableCollection<int>。不要忘記將集合初始化爲一些有意義的值,這裏我使用默認的構造函數初始化。

using System.Collections.ObjectModel; 
using System.Runtime.Serialization.Json; 
using Windows.Storage; 

//Add your own generic implementation of the collection 
//and make changes accordingly 
private ObservableCollection<int> temp; 

private string file = "temp.json"; 

private async void saveToFile() 
{ 
    //add your items to the collection 
    temp = new ObservableCollection<int>(); 

    var jsonSerializer = new DataContractJsonSerializer(typeof(ObservableCollection<int>)); 

    using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(file, CreationCollisionOption.ReplaceExisting)) 
    { 
     jsonSerializer.WriteObject(stream, temp); 
    } 
} 

private async Task getFormFile() 
{ 
    var jsonSerializer = new DataContractJsonSerializer(typeof(ObservableCollection<int>)); 

    try 
    { 
     using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(file)) 
     { 
      temp = (ObservableCollection<int>)jsonSerializer.ReadObject(stream); 
     } 
    } 

    catch 
    { 
     //if some error is caught while reading data from the file then initializing 
     //the collection to default constructor instance is a good choice 
     //again it's your choice and may differ in your scenario 
     temp = new ObservableCollection<int>(); 
    } 
} 

要添加一些功能代碼,您還可以有一個ensureDataLoaded()功能,將確保數據已經從JSON文件中讀取。

public async Task ensureDataLoaded() 
{ 
    if (temp.Count == 0) 
     await getFormFile(); 

    return; 
} 

使用全局變量temp(具有ObservableCollection)調用ensureDataLoaded功能之前。這將避免一些不必要的NullPointerExceptions

相關問題