How to get the current executable's path in C# (Code sample)
Sometimes you may want to get the current executable file path of your C# program. The working folder is needed to access settings, database, images, or resource files residing in the same directory as the currently running C# executable file of your program.
There are several options to find the current executable path in C#. But we have found the one that is working both for C# .NET Console Applications and for C# Windows Forms Applications:
//This will give us the full name path of the executable file:
//i.e. C:\Program Files\MyApplication\MyApplication.exe
string strExeFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
//This will strip just the working path name:
//C:\Program Files\MyApplication
string strWorkPath = System.IO.Path.GetDirectoryName(strExeFilePath)
The variable strWorkPath
will contain just the current path of executable residing in. You can use it later to access your settings or asset files:
//C:\Program Files\MyApplication\Settings.xml
string strSettingsXmlFilePath = System.IO.Path.Combine(strWorkPath, "Settings.xml");
Please be careful when storing the settings in the Program Files folder, This folder is protected by Windows security policy for non-administrative accounts. For user accounts, the settings files are automatically redirected to the respective folder inside AppData folder. So if the user runs the program twice, one time using the administrator account, and the second time using the user account, they may get two separate settings files, which may lead to confusion. So, for storing the settings it is better to use dedicated folders. As a developer of quality software, you may want your app to work on as much computers as possible.
Further reading may be here.