Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect to an MDF database file?

Tags:

I'm experimenting in connecting a C# app to an MDF database for the first time, and I need a little help ..

I made a small MDF database file in Visual Studio 2010, then created another project and imported the file into the project itself.

I am not trying to connect to the MDF file via code. Here the code I'm using:

namespace DBtestApp1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }         System.Data.SqlClient.SqlConnection con;         private void Form1_Load(object sender, EventArgs e)         {             con = new System.Data.SqlClient.SqlConnection();             con.ConnectionString = "DataSource=.\\SQLEXPRESS; AttachDbFilename =SampleDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";             con.Open();             MessageBox.Show("Connection opened");             con.Close();             MessageBox.Show("Connection closed");         }     } } 

When I run the application, I get an exception at the line where I define the connection string, and the exception has this message at the top of the stack:

System.ArgumentException: Keyword not supported: 'datasource'. 

Can someone point me in the right direction ?

like image 303
Ahmad Avatar asked Jan 19 '12 13:01

Ahmad


People also ask

How do I connect to a MDF file in SQL Server?

Run SQL Server management studio as an administrator and attach the database. Explicitly grant full control access to the MDF file and LDF file of the database. To do that, Right-click the database files Select the security tab select the appropriate user and grant full control to the user.

What program will open MDF files?

Aside from Alcohol 120%, these files are also used by other CD burners such as MagicISO, Daemon Tools, PowerDVD as well as the IsoBuster. MDF files can be opened by these applications but the application called H+H Software Virtual CD can also open MDF files.


1 Answers

Add space between Data Source

 con.ConnectionString = @"Data Source=.\SQLEXPRESS;                           AttachDbFilename=c:\folder\SampleDatabase.mdf;                           Integrated Security=True;                           Connect Timeout=30;                           User Instance=True"; 
like image 61
KV Prajapati Avatar answered Sep 18 '22 06:09

KV Prajapati