Search code examples
c#sql.net-coresqlclientdatadirectory

Can't connect to localdb when using [DataDirectory] in Windows Forms C# .NET Core


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.


Solution

  • finally found my solution , i was using System.Data.SqlClient which doesn't support |DataDirectory| in: AttachDbFilename= . the new SqlClient Provider package : Microsoft.Data.SqlClient is what should be used from now on which supports AppDomains and |DataDirectory| macro in AttachDbFilename=

    for using the System.Data.SqlClient the DB location in the connection string should be retrieved using : AppDomain.CurrentDomain.BaseDirectory so the connection string for System.Data.SqlClient Should be like this :

    cstr = @"server=(localdb)\MSSQLLocalDB;AttachDbFilename="+ AppDomain.CurrentDomain.BaseDirectory+"Database.mdf ; Integrated Security = True";
    

    this should fix the problem