How do I give an SqlConnection a string as the AttachDbFilename?


How do I give an SqlConnection a string as the AttachDbFilename?



I'd like to have a string be used as the AttachDbFilename in my SqlConnection.


AttachDbFilename


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?


AttachDbFilename


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");
}




1 Answer
1



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


databasePath


string.Format


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.





I tried that code and the dataBaseConnection is stale and the debugger says "The value of this item is stale due to a problem that occured while evaluating it".
– serialconnectorzrcool
Jun 29 at 17:00






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift