Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection string with relative path to the database file

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.

like image 437
Martin Avatar asked Dec 02 '09 15:12

Martin


People also ask

What is a connection string in database?

A connection string is a string that contains information about a data source (usually a database engine), as well as the information necessary to connect to it.

How do I create a database connection string?

Right-click on your connection and select "Properties". You will get the Properties window for your connection. Find the "Connection String" property and select the "connection string". So now your connection string is in your hands; you can use it anywhere you want.

How do I connect to a SQL Server connection string?

You can either use the new operator to make that directly. For example: SqlConnection conn = new SqlConnection( new SqlConnectionStringBuilder () { DataSource = "ServerName", InitialCatalog = "DatabaseName", UserID = "UserName", Password = "UserPassword" }. ConnectionString );


2 Answers

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); 
like image 179
Nime Cloud Avatar answered Oct 20 '22 00:10

Nime Cloud


Try this code to the working directory if database file exists like below.

D:\HMProject\DataBase\HMProject.sdf

string Path = Environment.CurrentDirectory; string[] appPath =  Path.Split(new string[] { "bin" }, StringSplitOptions.None); AppDomain.CurrentDomain.SetData("DataDirectory", appPath[0]); 

Connection string for .sdf file

<add name="LocalDB" connectionString="metadata=res://*/Client.HMProject.csdl|res://*/Client.HMProject.ssdl|res://*/Client.HMProject.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;Data Source=|DataDirectory|\Database\HMProjectDB.sdf;Password=HMProject;Persist Security Info=False;&quot;" providerName="System.Data.EntityClient" />

Thanks

ck.Nitin (TinTin)

like image 45
Ck.Nitin Avatar answered Oct 19 '22 22:10

Ck.Nitin