C# 如何在LocalStorage中保存文件?

C# 如何在LocalStorage中保存文件?,c#,xaml,windows-phone-8.1,C#,Xaml,Windows Phone 8.1,我有一个明显的收集。我想在其中插入各种元素,然后将新创建的文件保存在LocalStorage中。我该怎么做 SQLiteAsyncConnection conn = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Database.db"), true); await conn.CreateTableAsync<Musei>(); var Dbase = Path.Co

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

我正在使用json文件存储在内存中。JSON是一种轻量级的消息交换格式,被广泛使用。如果你想要一些不同的文件格式,你必须对代码做一些轻微的修改

您的集合将在保存时序列化到内存中,并且在从内存读回时必须进行反序列化

添加您自己的集合的通用实现。为了创建您的情况,我使用了一个简单的ObservableCollection。不要忘记将集合初始化为一些有意义的值,这里我使用默认构造函数初始化

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>();
    }
}

在使用全局变量temp之前,ObservaleCollection调用ensureDataLoaded函数。这将避免一些不必要的NullPointerException。

运行现有代码时会遇到哪些问题。。请提供更多信息我想将“favmusei”保存在本地存储中这很好..但是运行现有代码时会遇到什么问题。。不要只说我想将favmusei保存在本地存储中调试代码并告诉我们故障发生的位置。听起来你可能会从研究序列化中受益。不过,这是否是你的选择,将取决于博物馆中的物品是由什么组成的。基本规则是数据可以很容易地序列化和反序列化,尤其是事件处理程序和委托不能或不能安全地进行序列化。
public async Task ensureDataLoaded()
{
    if (temp.Count == 0)
        await getFormFile();

    return;
}