how to link correctly to a local database


New member
Oct 11, 2021
Programming Experience
I have a c# application with a SQL database.
For now the database is located in the root directory of the solution (standard location).
I also see that each time I run the application for testing and such. The database is being copied to the bin/debug directory.

So now I'm wondering how to setup a correct connectionString?

If I link the database with a full path like this :

m_sConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Steven\\Source\\Repos\\Vetex\\Dashboard_Villars_dotnet\\Database.mdf;Integrated Security=True";

Everything seems to work fine, but I doubt this is the correct way.
What will happen when I deploy my application? This way the wrong file will be referenced?

In other forums I see that people suggest on using "|datadirectory|"

but if I try it like this :

m_sConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True";

the application works and I can write to the database, but I have the impression that somehow the new data is being discarted.
When I re open the application I cannot find the new data.

I'm 100% sure that the data is written in the database because I always check how many rows are being written :

int nRows = command.ExecuteNonQuery();
MessageBox.Show(nRows.ToString() + " row(s) were succesfully written to database!");

This always return 1 row that was succesfully written to the database.


Staff member
Apr 6, 2019
Chesapeake, VA
Programming Experience
The reason why it looks like you are losing data is because the default setting of Visual Studio to to replace the database file in the build directory with the database in the project directory at build time. You need to change the build options to not replace the file.
Top Bottom