I have a SQLite database from another project and I want to use it in a UWP application. But I don't know how to import this database to the project and!
1 Answers
I can create a new Database and use it but I don't know how to copy database file from project. I use from SQLite.Net-PCL nuget package.
For how to access an exist file, there are two locations that all apps can access. Details please reference the file-access-permissions.
One is Application install directory
. As @Henk Holterman said, you can import your existed database file into your project by right-click one folder and select Add->Existing item to add your database file to the project. Pay attention the file's Build action
property need to be set to content
. Details please see the following picture.
Suppose you already had a database file Sun.db
added to the Assets folder, and now you can connect to it by the following code( use the SQLite.Net-PCL Nuget Package).
path = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, @"Assets\Sun.db");
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path))
{
}
But this folder is read only. Another location is Application data locations
which can read/write. You can copy the database file from install directory to the application data directory for using. The following code example is for connecting a database file that in the local folder.
StorageFile file;
try
{
file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Sun.db");
}
catch
{
StorageFile Importedfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Sun.db"));
file = await Importedfile.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder);
}
path = file.Path;
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path))
{
conn.CreateTable<User>();
}