Home > Back-end >  Is it possible to point my connection string to the folder of my exe file
Is it possible to point my connection string to the folder of my exe file

Time:07-29

I'm making a windows forms project and I was wondering if its possible to point the connection string for my .mdf file to the folder of the programs .exe file so that when I send the program to my someone else it can still find the file.

This is what I'm using right now but I want it to point to the .exe file folder instead if possible. I've tried everything I can find on this topic and I can't figure it out.

string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Martin\source\repos\Guldkortet\Guldkortet\Kortregister.mdf;Integrated Security=True";

CodePudding user response:

If you mean that your database is in the folder of your main .exe file and you want to get the path, use System.Reflection, more specifically - the assembly's Location property to get the path at runtime, for example:

string assemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

and construct the connection string using it:

string connectionString = String.Format("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename={0}\\Kortregister.mdf;Integrated Security=True", assemblyPath);

There are other options, but that's the answer to your question.

CodePudding user response:

string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Kortregister.mdf;Integrated Security=True";

The |DataDirectory| placeholder will be resolved at run time and what it resolves to depends on the type of application. For a WinForms app, it will resolve to the program folder by default, including while debugging. If you copy your app to a different folder or different machine, it will just work. If you deploy using ClickOnce then a dedicated data directory is created outside the program folder and that path will be resolved correctly.

Note that, because no code is required to construct the connection string, it can be stored in a config file or the like. That means that a user can modify it after deployment if they want their database in a different place or, perhaps, permanently attached to an instance.

  • Related