Export Sqlite database from Windows Store App

2019-08-28 04:28发布

问题:

I've got a Sqlite database which I populate inside a Windows Store app. Now I'd like to have said database availiable when reinstalling the app, therefore I have to add it to my project as a file, if I'm right.

Now I'm trying to export the database file using the PickSaveFileAsync()-Method. Unfortunately I don't really know how to go about this once I've got the file. Here's what I've got so far:

    private async void exportDB_Click(object sender, RoutedEventArgs e)
    {
        StorageFile database = await ApplicationData.Current.LocalFolder.GetFileAsync("Hashes.db");
        var picker = new FileSavePicker();
        picker.FileTypeChoices.Add("Database File", new string[] { ".db" });
        picker.CommitButtonText = "Save DB";
        picker.SuggestedFileName = "Database";
        StorageFile file = await picker.PickSaveFileAsync();
        if (file != null)
        {
            // What to do here?
        }
    }

回答1:

I'm having a hard time figuring out what exactly you are trying to achieve.

Looking at the code it seems that you want to copy your database file to a user defined location. To do this just add the following code inside your if block:

using (var srcStream = await database.OpenStreamForReadAsync())
{
    using (var destStream = await file.OpenStreamForWriteAsync())
    {
        await srcStream.CopyToAsync(destStream);
    }
}

Reading the introductory text it seems you're trying to include the file with your application. In this case you should indeed add it as Content to your project. You can then access it from code as follows:

var dbFile = Package.Current.InstalledLocation.GetFileAsync(@"db\Hashes.db");

In case you didn't know, you can find the files in LocalFolder in the following directory:

C:\Users\Username\AppData\Local\Packages\PackageName\LocalState