Ahmad Ahmad - 1 year ago 78
SQL Question

How do I connect to an MDF database file?

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()
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";
MessageBox.Show("Connection opened");
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 ?

Answer Source

Add space between Data Source

 con.ConnectionString = @"Data Source=.\SQLEXPRESS;
                          Integrated Security=True;
                          Connect Timeout=30;
                          User Instance=True";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download