Connection String with Relative Path to the Database File

App.config connection string relative path

You can specify a relative path as described in Lefty's answer.

However this will be relative to the current working directory, which will not necessarily be the directory containing your executable.

One way round this is to modify the connection string before using it, e.g.

In app.config:

 connectionString="data source={AppDir}\data\EmailDatabase.sqlite

In your code:

ConnectionStringSettings c = ConfigurationManager.ConnectionStrings[name];    
if (c == null)
{
... handle missing connection string ...
}
string fixedConnectionString = c.ConnectionString.Replace("{AppDir}", AppDomain.CurrentDomain.BaseDirectory);
... use fixedConnectionString

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

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.

EFCore SQLite connection string with relative path in asp.net

You'll have to fix up the relative paths at runtime:

var builder = new SqliteConnectionStringBuilder(connectionString);               
builder.DataSource = Path.GetFullPath(
Path.Combine(
AppDomain.CurrentDomain.GetData("DataDirectory") as string
?? AppDomain.CurrentDomain.BaseDirectory,
builder.DataSource);
connectionString = builder.ToString();

How can I change my connection string's absolute path to relative path?

Make your connection string setting as follows:

<connectionStrings>
<add name="movies_db.mdf" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename={%FileName%};Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>

Then in your code use the connection string as follows:

ConfigurationManager.ConnectionStrings["movies_db.mdf"].ConnectionString.Replace("{%FileName%}",
Server.MapPath("~/App_Data/movies_db.mdf"));


Related Topics



Leave a reply



Submit