C # - Knowing the location of the database file dynamically

0

I'm doing a program using C # in WPF, and I need to access the database dynamically, in this case I'm using a .mdf file. In code I have the connectionString like this:

string stringConexao = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\PAP\Trabalhos\Trabalhos\Trabalhos.mdf; Integrated Security=True";

I want to replace "E: \ PAP \ Jobs \ Jobs \ Jobs.mdf" with a dynamic way to find the database, so that I can then use the program outside of my computer.

The first "\ Jobs \" corresponds to where "Jobs.sln" is, the other folder "Jobs" and "packages". In the next folder is where you have all the .cs, .xaml, etc.

One of the solutions I found was to put the database inside Debug, however I do not think it's the right way to do it.

Thanks in advance.

    
asked by anonymous 24.11.2018 / 00:12

3 answers

0

HAVE AS REFERENCE, THE APPLICATION FOLDER. E:\PAP\aplicativo.exe

' |DataDirectory|\ ' is the folder where ' aplicativo.exe ' is.

CASE 1: ' \aplicativo.exe ' and ' \Trabalhos.mdf ' are in the same folder
OR BE: ' E:\PAP\aplicativo.exe ' and ' E:\PAP\Trabalhos.mdf '

AttachDbFilename=|DataDirectory|\Trabalhos.mdf;

CASE 2: ' \aplicativo.exe ' and ' \Trabalhos.mdf ' are in DIFFERENT folders
OR BE: ' E:\PAP\aplicativo.exe ' and ' E:\PAP\Trabalhos\Trabalhos\Trabalhos.mdf '

AttachDbFilename=|DataDirectory|\Trabalhos\Trabalhos\Trabalhos.mdf;

SUMMARY: Use this code. this code. that works.

string stringConexao = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Trabalhos\Trabalhos\Trabalhos.mdf; Integrated Security=True";
    
24.11.2018 / 03:18
0

Hello, the answer is simple.

Make this database always present in the root directory of the project executable.    So you can use the line of code that I will show below to get the location of the project folder:      Application.StartupPath ;

I hope I have helped !!

    
24.11.2018 / 17:45
0

I've been researching and found 2 ways to find the root directory of a WPF application.

You can do this:

System.AppDomain.CurrentDomain.BaseDirectory

Or so:

System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)

I hope this time I have helped! :)

    
25.11.2018 / 18:35