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.
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.
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.
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 );
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);
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="Data Source=|DataDirectory|\Database\HMProjectDB.sdf;Password=HMProject;Persist Security Info=False;"" providerName="System.Data.EntityClient" />
Thanks
ck.Nitin (TinTin)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With