Keshav
Keshav

Reputation: 103

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

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();

Upvotes: 2

Views: 16017

Answers (4)

spec
spec

Reputation: 439

In an ASP CORE project if your db is in Data folder, write the following code in startup.cs:

public void ConfigureServices(IServiceCollection services)
{
      services.AddDbContext<MyContext>(options =>
          options.UseSqlite("Data Source=" + 
          Path.Combine(Directory.GetCurrentDirectory(), "Data\\sqlite.db"))
      );
}

Upvotes: 0

Keshav
Keshav

Reputation: 103

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.

Upvotes: 2

Roxy&#39;Pro
Roxy&#39;Pro

Reputation: 4444

I guess you need to modify your connection string, so for basic connect to SQL LITE DATABASE, you would do this:

Data Source=c:\mydb.db;Version=3;

enter code here

In memory database:

Data Source=:memory:;Version=3;New=True;

With password

Data Source=c:\mydb.db;Version=3;Password=myPassword;

You could do this also in your c# code:

var connectionString = @"data source=c:\TestData\testsqldata.s3db; Version=3;"
            connection = new SQLiteConnection(connectionString);
            connection.Open();

Upvotes: 0

Azar Shaikh
Azar Shaikh

Reputation: 449

try this

var parentdir =Path.GetDirectoryName(System.Windows.Forms.Application.StartupPath);

Upvotes: 0

Related Questions