简体   繁体   中英

Use .MDF file in c#

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.

Check the following 3 things:

  1. Make sure your MDF file was created by the same or older version of SQL Server than the one installed on the target machine.

  2. Make sure that the SQL Server on target machine doesn't already have a database with the same name.

  3. 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.

  4. You may want to look into the |DataDirectory| feature too, intsead of GetCurrentDirectory() .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM