Search code examples
c#wpfsqlite

Can't access SQLite database stored within file structure of WPF application namespace (Visual Studio)


I am creating a WPF app using Visual Studio and am wanting to store a database within the projects "Assets" folder in order to make the app fully self contained.

I created the database externally (didn't use migrations or equivalent coded constructs which I have seen done) and have tried to access the database through a path similar to what I used to access the images also stored within the "Assets" folder Assets\data\database.db however the program then throws an error when I try and access the database saying that it cannot be found.

Database access

namespace Project
{
    public class LoadDb
    {
        public LoadDb()
        {
            ReadDatabase();
        }

        void ReadDatabase()
        {

            using (SqliteConnection conn = new SqliteConnection(@"Data Source=..\Assets\data\database.db"))
            {
                conn.Open();

                SqliteCommand command = new SqliteCommand("Select * from Data", conn);
                SqliteDataReader reader = command.ExecuteReader();

                var dataList = new List<KeyValuePair<int, string>>();
                while (reader.Read())
                {
                    dataList.Add(new KeyValuePair<int, string>(reader.GetInt32(reader.GetOrdinal("dataId")), reader.GetString(reader.GetOrdinal("Name"))));
                }
                reader.Close();
                conn.Close();
            }
                

        }
    }
}

Changing @"Data Source=C:\(full path)\Assets\data\database.db" does work however that path is dependent on the location of the app which I didn't think was what I was wanting.

I am very new to WPF and C# so have been learning from various tutorials and forums but nothing I can find has anything similar to what I am wanting, I have seen storage within C:\ProgramData\ but (unless I am thinking incorrectly) that wouldn't be a self contained application?

----Edit----

This is a screenshot of the file structure within the project namespace within Visual Studio. file layout


Solution

  • If you put your Assets folder near your application *.exe file, the following code will fix the issue. (Tested - it connects to the database.)

    void ReadDatabase()
    {
        string appFolder = System.AppDomain.CurrentDomain.BaseDirectory;
        string dbFilePath = System.IO.Path.Combine(appFolder, "Assets\\data\\database.db");
        string connectionString = $"Data Source={dbFilePath}";
        using (SqliteConnection conn = new SqliteConnection(connectionString))
        {
            conn.Open();
    
            // Other stuff.
        }
    }