I installed VS2019 and started training, I'm trying to connect to my DB using [DataDirectory] the DB File is in my Debug folder I'm using the following Conn string cstr = @"server=(localdb)\MSSQLLocalDB;AttachDbFilename=[DataDirectory]\test.mdf;Integrated Security = True;"; but I'm getting this error
An attempt to attach an auto-named database for file [DataDirectory]\test.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share
but it will work if I change [datadirectory] with another fixed location like D:\Test.mdf
My Code:
string cstr;
SqlConnection cnn;
cstr = @"server=(localdb)\MSSQLLocalDB;AttachDbFilename=[DataDirectory]\Test.mdf;Integrated Security = True;";
cnn = new SqlConnection(cstr);
cnn.Open();
MessageBox.Show("Connection Open !");
cnn.Close();
Please help.
finally found my solution , i was using
System.Data.SqlClientwhich doesn't support |DataDirectory| in:AttachDbFilename=. the new SqlClient Provider package :Microsoft.Data.SqlClientis what should be used from now on which supports AppDomains and|DataDirectory|macro inAttachDbFilename=for using the System.Data.SqlClient the DB location in the connection string should be retrieved using :
AppDomain.CurrentDomain.BaseDirectoryso the connection string forSystem.Data.SqlClientShould be like this :this should fix the problem