0

In a CRUD class I have declared the following connection string:

private static string dbConnection = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + System.AppDomain.CurrentDomain.BaseDirectory + "\\PlexSeries.mdf;Integrated Security=True;Connect Timeout=30";

And the following GET method:

public DataTable Get()
{
     DataSet dataset = new DataSet();

     using (SqlConnection connection = new SqlConnection(dbConnection))
     {
         try
         {
              SqlDataAdapter adapter = new SqlDataAdapter();
              adapter.SelectCommand = new SqlCommand("SELECT * FROM dbo.Series", connection);
              adapter.Fill(dataset);
              return dataset.Tables["Table"];
         }
         catch (Exception ex)
         {
             MsgBox.Show(ex.Message, "Error", MsgBox.Buttons.OK, MsgBox.Icon.Error, MsgBox.AnimateStyle.FadeIn);
             return null;
         }
     }
}

When the application is run in the debug folder of the solution everything works fine.

But when I copy the debug folder to an other location ...

Upon getting to the line adapter.Fill(dataset), I get the following error:

Error Image

I tried to solve this by using a relative path to the database file but that didn't solve the problem.

In the previous version of this solution this was not a problem but that was build with Visual Studio 2019 and now I am using Visual Studio 2022.

Any tips on how to solve this?

Charlieface
  • 52,284
  • 6
  • 19
  • 43
RonnyMees
  • 1
  • 1
  • Have you tried using less backslashes? It seems like `System.AppDomain.CurrentDomain.BaseDirectory` already ends with a backslash, so you shouldn't need one (escaped or otherwise) before `PlexSeries.mdf`. – AlwaysLearning Jul 15 '23 at 12:38
  • Just tried that, same result :-( – RonnyMees Jul 15 '23 at 13:45
  • Do yourself a favour and don't use `AttachDbFilename` it's really problematic. Instead attach your database normally using `CREATE DATABASE FOR ATTACH`, and connect to it using `Initial Catalog=YourDatabase` – Charlieface Jul 16 '23 at 02:27

0 Answers0