How to specify a relative SQLite database path in C#?

10,122

Alright, I figured it out guys.

string relativePath = @"Database\Database.sqlite";
var parentdir = Path.GetDirectoryName(Application.StartupPath);
string myString = parentdir.Remove(parentdir.Length -34, 34);
string absolutePath = Path.Combine(myString, relativePath);
string connectionString = string.Format("Data Source={0};Version=3;Pooling=True;Max Pool Size=100;", absolutePath);
m_dbConnection = new SQLiteConnection(connectionString);
m_dbConnection.Open();

I removed the characters from the parentdir till SampleApplication\ and added it with the relativePath. That makes an absolutePath to the database. The number 34 in the third line signifies how many characters to be remove from the end of parentdir.

Share:
10,122
Keshav
Author by

Keshav

A masters student of 'Embedded System Design' and part time student employee at Siemens CT. Started coding in C# recently and likes it.

Updated on June 04, 2022

Comments

  • Keshav
    Keshav almost 2 years

    My database is located outside the application folder Example:

    Database: SampleApplication\Database\Database.sqlite

    Application: SampleApplication\Application\program.cs

    My code is as below.

    string relativePath = @"SampleApplication\Database\Database.sqlite";
    string currentPath;
    string absolutePath;
    string connectionString;
    currentPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
    absolutePath = Path.Combine(currentPath, relativePath);
    connectionString = string.Format("Data Source={0};Version=3;Pooling=True;Max Pool Size=100;", absolutePath);
    m_dbConnection = new SQLiteConnection(connectionString);
    m_dbConnection.Open();