0

Sadly, the answer to the following question does not solve my problem: SQLite - Could not open database file

I know that the folder exists, but still run into the following exception:

SQLite.SQLiteException: 'Could not open database file: C:\Users\david\data.db (CannotOpen)'

using (var conn = new SQLiteConnection(@"C:\Users\david\data.db"))
{
    conn.CreateTable<DBItem>();
    var item = new DBItem();
    item.TextData = addEntry.Text;
    conn.Insert(item);
}
JohnWick
  • 4,929
  • 9
  • 37
  • 74

1 Answers1

0

I added this static Constants class to my project, as recommended here: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/databases

public static class Constants
{
    public const string DatabaseFilename = "TodoSQLite.db3";

    public const SQLite.SQLiteOpenFlags Flags =
        // open the database in read/write mode
        SQLite.SQLiteOpenFlags.ReadWrite |
        // create the database if it doesn't exist
        SQLite.SQLiteOpenFlags.Create |
        // enable multi-threaded database access
        SQLite.SQLiteOpenFlags.SharedCache;

    public static string DatabasePath
    {
        get
        {
            var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            return Path.Combine(basePath, DatabaseFilename);
        }
    }
}

And updated my calling code to the following:

using (var conn = new SQLiteConnection(Constants.DatabasePath))
{
    conn.CreateTable<DBItem>();
    var item = new DBItem();
    item.TextData = addEntry.Text;
    conn.Insert(item);
}

And it works now. I had been following a slightly outdated tutorial that didn't mention this requirement.

I'm still curious why I wasn't able to just simply use "C:\Users\david\data.db"?

JohnWick
  • 4,929
  • 9
  • 37
  • 74