Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 14: 'unable to open database file'.'

给你一囗甜甜゛ 提交于 2020-04-16 05:49:12

问题


I get this error Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 14: 'unable to open database file'.' when I try to run this code, it is a UWP application and I am using sqlite

private void btnContinue_Click(object sender, RoutedEventArgs e)
        {
            string datasource = @"F:\Curtis\Documents\Capstone\Capstone\Database\BobDB.db"; ;


            using (SqliteConnection conn = new SqliteConnection(@"Data Source = " + datasource))
            {
                conn.Open();
                SqliteCommand command = conn.CreateCommand();
                command.CommandText = "Select TestTableTXT from TestTable;";
                using (SqliteDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        DatabaseTextBlock.Text = reader.GetString(0);
                    }
                }



                    conn.Close();
            }
        }

回答1:


UWP apps are running in the sandbox and when you run them they are installed into it. They are not running in your source code bin folder of your project. In order to make your code up and running add your db file to your project Assets folder Assets\BobDB.db. Set Build Action of this file to Content. The good thing is that our file is now included to our Installed app folder. The bad thing is that it is read only. To overcome it we need to copy it to local app folder:

public MainPage()
{
    this.InitializeComponent();
    Loaded += MainPage_Loaded;
}

private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    string targetDbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Database\\BobDB.db");
    if (!File.Exists(targetDbPath)) 
    {
        var installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
        using (var input = await installedLocation.OpenStreamForReadAsync("Assets\\BobDB.db")) 
        {
            using (var output = await Windows.Storage.ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("Database\\BobDB.db", Windows.Storage.CreationCollisionOption.FailIfExists))
            {
                await input.CopyToAsync(output);
            }
        }                
    }       


    using (SqliteConnection conn = new SqliteConnection(@"Data Source = " + targetDbPath))
    {
        conn.Open();
...


来源:https://stackoverflow.com/questions/60807553/microsoft-data-sqlite-sqliteexception-sqlite-error-14-unable-to-open-databas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!