waqas shah

waqas shah

  • 1.7k
  • 78
  • 8k

Add Data Directory in connection string

Jun 30 2015 7:12 AM
I created an windows form application in c# during development i used following connection string and it works fine
<connectionStrings> <add name="myconnection" connectionString="Data Source=ABC-PC\SQLEXPRESS;Initial Catalog=mydatabase;Integrated Security=True"/> </connectionStrings>
but now i need to deploy application on client machine and i have to add data directory option in my connection string and i did this as
<connectionStrings> <add name="myconnection" connectionString="Data Source=.\SQLEXPRESS; Integrated Security=True; User Instance=True;AttachDbFilename=|DataDirectory|\mydatabase.mdf;  Initial Catalog=mydatabase; "/> </connectionStrings>
when i changed string then it threw and error
 
Unable to open the physical file "D:\Other Projects\Employee\Employee\bin\Debug\mydatabase.mdf". Operating system error 2: "2(The system cannot find the file specified.)". Cannot attach the file 'D:\Other Projects\Employee\Employee\bin\Debug\mydatabase.mdf' as database 'mydatabase'. 
 
and calling connection string as 
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
 I used SQL server 2008.

Answers (8)