Reputation: 3
I'd like to have a string be used as the AttachDbFilename
in my SqlConnection
.
However when I feed it a string it doesn't work and just gives me a null or invalid connection/failure. How do I properly provide AttachDbFilename
as a string value in place of the normal set path?
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string databasePath = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
SqlConnection dataBaseConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=databasePath;Integrated Security=True;Connect Timeout=30;User Instance=True");
}
Upvotes: 0
Views: 135
Reputation: 783
You have databasePath
inside the string literal so right now you are trying to attach with a Db Filename of "databasePath", which I'm assuming doesn't exist. One way you could do this is to use string.Format
, so you would do something like this
string databasePath = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
SqlConnection dataBaseConnection = new SqlConnection(string.Format(@"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;Connect Timeout=30;User Instance=True", databasePath);
Or, for something even more organized, you could use the SQLConnectionStringBuilder class to build a connection string for you, and then just set the AttachDbFilename property of the builder to the string that you want.
Upvotes: 1