Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App.config connection string relative path

I need to set in the app.config the sqlite connection string. I want to set the path relative to the debug/release folders the database file will be copied to those folders.

<add name="EmailsSQLite" connectionString="data source=c:\Users\Test\Documents\Visual Studio 2008\Projects\TestConsole\Emails\data\EmailDatabase.sqlite" providerName="System.Data.SQLite"/>

and I want to have something like:

<add name="EmailsSQLite" connectionString="data source=\data\EmailDatabase.sqlite" providerName="System.Data.SQLite"/>

Is that possible?

like image 442
Radu D Avatar asked Feb 15 '11 09:02

Radu D


People also ask

Where to store db connection string?

Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file.

How to get connection string in console application c#?

In this window, click Console Application under Visual C#. Give the name of your application as "Database_Connection_Application" and then click OK. Now, specify a name, then click in the Type cell. In the drop-down box choose "Connection String".


1 Answers

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
like image 158
Joe Avatar answered Sep 20 '22 19:09

Joe