Many times we need to know executable path of Application and some time we need to know the path of assembly which is loaded. There are many options to get the location but not all are good as we think.
So be careful and use correct method to get application location based on your needs. Here is small tutorial in which we discuss different methods to get location of executable.
The path for the executable file that started the application.
The path and executable name for the executable file that started the application.
The base directory that the assembly resolver uses to probe for assemblies.
Gets the current working directory of the application.
Gets or sets the fully qualified path of the current working directory.
Gets the full path or UNC location of the loaded file that contains the manifest.
Gets the location of the assembly as specified originally.
Lets test out these options, so that I make a simple Windows Forms Application and add following code and move my exe to c drive.
label1.Text = "Application.StartupPath : " + Application.StartupPath; label2.Text = "Application.ExecutablePath : " + Application.ExecutablePath; label3.Text = "AppDomain.CurrentDomain.BaseDirectory : " + AppDomain.CurrentDomain.BaseDirectory; label4.Text = "System.IO.Directory.GetCurrentDirectory : " + System.IO.Directory.GetCurrentDirectory(); label5.Text = "Environment.CurrentDirectory : " + Environment.CurrentDirectory; label6.Text = "Assembly.Location : " + this.GetType().Assembly.Location; label7.Text = "Assembly.GetExecutingAssembly().CodeBase : " + System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
and see the results below.
So every option seems to be correct. But wait what if run this application from other application i.e cmd.exe
See the result of System.IO.Directory.GetCurrentDirectory and Environment.CurrentDirectory are different of others.
And what if I load assembly from other location, for that I copy this assembly to D drive and load this form from C drive exe. Now see the results.
At last run application from cmd.
If we want to get Running Application Path, and Application is Windows Form application then we can use.
Application.StartupPath Application.ExecutablePath AppDomain.CurrentDomain.BaseDirectory
If loaded assembly is in same folder then we can also use
If we want to get location of loaded assembly, then use above mentioned methods.