Search code examples
c#.netcsharpcodeprovider

How to add data directory in connection string to deploy application on client machine?


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.


Solution

  • After a lot of research plus hit an try i found solution that connection string is correct a thing that i did is to copy database files from SQL server's folder to project folder. Now it is working fine according to my requirement.