Connection string with relative path to the database file

Martin picture Martin · Dec 2, 2009 · Viewed 110.9k times · Source

I load data from sdf database in winforms App. I use full path to the database file . Example :

conn = new SqlCeConnection

{

ConnectionString ="Data Source=F:\\My Documents\\Project1\\bin\\Debug\\Database.sdf"

};

I d like use a relative path to the database file. For example. I have sdf file in folder F:\My Documents\Project1\bin\Debug\Data\file.sdf and I want use relative path in connection string. Any advice ? Thank you.

Answer

Nime Cloud picture Nime Cloud · Aug 4, 2011

Relative path:

ConnectionString = "Data Source=|DataDirectory|\Database.sdf";

Modifying DataDirectory as executable's path:

string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = (System.IO.Path.GetDirectoryName(executable));
AppDomain.CurrentDomain.SetData("DataDirectory", path);