Connecting to MDF Database File in C#
Connecting to a Microsoft Data Format (MDF) database file in C# can present challenges for first-timers. One common issue is encountering an invalid connection string syntax.
Error Encountered
When attempting to connect to an MDF database using the following code:
con.ConnectionString = "DataSource=.\SQLEXPRESS; AttachDbFilename =SampleDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
An exception is thrown with the message:
System.ArgumentException: Keyword not supported: 'datasource'.
Solution
The error originates from a missing space between "Data" and "Source" in the connection string. To resolve it, modify the connection string as follows:
con.ConnectionString = @"Data Source=.\SQLEXPRESS; AttachDbFilename=c:\folder\SampleDatabase.mdf; Integrated Security=True; Connect Timeout=30; User Instance=True";
Additional Considerations
The above is the detailed content of How to Correctly Connect to an MDF Database File in C#?. For more information, please follow other related articles on the PHP Chinese website!