Search code examples
c#ms-accessinstallationspecial-folders

How to add relative path to DB file for C#


I have a C# project and I have added a Access file (.mdb) by New Data Source option.

So a copy of it is always in my project folder. Now my connection string uses that path (C:\Users\PC\Visual Studio\Projects....). If I'm moving the project to another directory or machine I have to manually change the path. But if I'm making the app as installable, this might not be possible.

How to make the db path relative to the project?


Solution

  • When configuring your installer, you specify which folder the .mdb file will go to. You might choose to put it in the same folder as your application's .exe file, or in the application's folder under AppData, or in the user's home folder, or any other place you like. Just as you specify this to the installer, you can specify it in your code using the Environment.SpecialFolder enumeration.

    The problem is that during development, your .mdb file is usually in the root of your project folder, which coincides with none of the above.

    What I do is that first of all, in project options I make sure that when my application launches during development, it always launches in the root folder of my project, not in the ./bin/Debug folder.

    Then, each time my application launches, I check whether my .mdb file is in the current directory of the application, and if it is, then this must be a development run, so I use it.

    Otherwise, this must be a deployment run, so I use the SpecialFolder enum to get the folder where the .mdb file ought to have been placed by the installer.