Question

I am building a Windows 8 application using sql-net and mvvmcross for data access to a sqlite database. This would be applicable to any Win-8 or Win-Phone app.

I need to install an existing sqlite file on app start.

When using the connection you use syntax such as this

 public FlashCardManager(ISQLiteConnectionFactory factory, IMvxMessenger messenger)
    {
        _messenger = messenger;
        _connection = factory.Create("Dictionary.sqlite");
        _connection.CreateTable<FlashCardSet>();
        _connection.CreateTable<FlashCard>();
    }

    public void CreateCard(FlashCard flashCard)
    {
        _connection.Insert(flashCard);

    }

That connection creates a file in: C:\Users\USER\AppData\Local\Packages\793fd702-171e-474f-ab3b-d9067c58709b_ka9b83fa3fse2\LocalState

My application uses an existing sqlite database file that I have created. I need to place it in this folder when the application is installed. How would I go about doing this?

Thanks, JH

Was it helpful?

Solution

Make sure you have the database file you want your app to start off with in one of your apps folders (as in the folders visible in visual studios solution explorer). For this example I'll call this folder "Assets"

All you need to do then is copy this file to the LocalState folder the first time your app runs. This can be done in App.xaml.cs

private async void InitializeAppEnvironment()
    {
        try
        {
            if (!(await AppHelper.ExistsInStorageFolder(AppHelper.localFolder, dbName)))
            {
                StorageFile defaultDb = await AppHelper.installedLocation.GetFileAsync("Assets\\" + dbName);
                await defaultDb.CopyAsync(AppHelper.localFolder);
            }
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine(e);
        }
    }

I made an AppHelper class to simplify accessing the app data folders, here's the parts I used above:

static class AppHelper
{
    public static StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
    public static StorageFolder localFolder = ApplicationData.Current.LocalFolder;

    public static async Task<bool> ExistsInStorageFolder(this StorageFolder folder, string fileName)
    {
        try
        {
            await folder.GetFileAsync(fileName);
            return true;
        }
        catch (FileNotFoundException)
        {
            return false;
        }
    }
}

OTHER TIPS

For a more detailed response on MVVM cross I found the current discussion about cross platform file placement in this discussion: Link

The current thought is that you have to inject platform specific code for this sort of functionality.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top