Reputation: 87
I have an .mdf
file. I want to use it in c# in desktop application.
This is my connection string :
string cwd = System.IO.Directory.GetCurrentDirectory();
string ConString = @"Data Source=.\SQLEXPRESS; AttachDbFilename=" + cwd + "\\SalaryProgram.mdf;Integrated Security=True;User Instance=True";
How can I use the .mdf
file in C# ?
I am getting this error :
An attempt to attach an auto-named database for file D:\Naresh Backup\SalaryProgram\Latest Work\SalaryProgram\SalaryProgram\bin\Debug\SalaryProgram.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Thanks in advance.
Upvotes: 0
Views: 3465
Reputation: 473
I’d really recommend that you attach this MDF file to your local instance regularly and then connect to database. Attaching mdf files in asp.net applications is not really the best way to go with this.
Just add connection string to your aplication config file
<connectionStrings>
<add name="yourConnectionString" connectionString=
"Data Source=(local); Initial Catalog=database_name;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Then use it in your code like this:
string ConString = ConfigurationManager.ConnectionStrings["yourConnectionString
"].ConnectionString
Upvotes: 0
Reputation: 5137
In one of my previous project (winform application in C#), I was using a DB say "EmployeeMaster".
Connection string that worked for me was:
"Data Source=(local)\SQLExpress;Initial Catalog=EmployeeMaster;Trusted_Connection=Yes;"
Give it a try.
Upvotes: 0
Reputation: 35460
Check the following 3 things:
Make sure your MDF file was created by the same or older version of SQL Server than the one installed on the target machine.
Make sure that the SQL Server on target machine doesn't already have a database with the same name.
Always prefer Path.Combine()
over direct concatenation of folder path and file name. Sometimes a function returns ending backslash character as part of the path, other times it doesn't. So direct concatenation can result in illegal paths.
You may want to look into the |DataDirectory| feature too, intsead of GetCurrentDirectory()
.
Upvotes: 1