如何在LocalStorage中保存文件?

时间:2015-04-21 20:48:15

标签: c# xaml windows-phone-8.1

我有ObservableCollection <T>。我想在其中插入各种元素,然后将新创建的文件保存在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);            
    }
}

1 个答案:

答案 0 :(得分: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