I see that there are some ways to get the application folder path:
Application.StartupPath
System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location)
AppDomain.CurrentDomain.BaseDirectory
System.IO.Directory.GetCurrentDirectory()
Environment.CurrentDirectory
System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
System.IO.Path.GetDirectory(Application.ExecutablePath)
What is the best way depending on the situation?
Note that not all of these methods will return the same value. In some cases, they can return the same value, but be careful, their purposes are different:
returns the
StartupPath
parameter (can be set when run the application)returns the current directory, which may or may not be the folder where the application is located. The same goes for
Environment.CurrentDirectory
. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).I have used this one successfully
It works even inside linqpad.
AppDomain.CurrentDomain.BaseDirectory
is probably the most useful for accessing files whose location is relative to the application install directory.In an ASP.NET application, this will be the application root directory, not the bin subfolder - which is probably what you usually want. In a client application, it will be the directory containing the main executable.
In a VSTO 2005 application, it will be the directory containing the VSTO managed assemblies for your application, not, say, the path to the Excel executable.
The others may return different directories depending on your environment - for example see @Vimvq1987's answer.
CodeBase
is the place where a file was found and can be a URL beginning with http://. In which caseLocation
will probably be the assembly download cache. CodeBase is not guaranteed to be set for assemblies in the GAC.I started a process from a Windows Service over the Win32 API in the session from the user which is actually logged in (in Task Manager session 1 not 0). In this was we can get to know, which variable is the best.
For all 7 cases from the question above, the following are the results:
Perhaps it's helpful for some of you, doing the same stuff, when you search the best variable for your case.
As Example :
btn_OpenFile
']C:\Users\Admin\Documents\Visual Studio 2015\Projects\MyProject\MyProject\abc.exe.
So, I'll do the Following :
btn_OpenFile_Click()
Process.Start(@Environment.CurrentDirectory+"\\..\\..\\abc.exe");
Note : "Environment.CurrentDirectory" return this path :
"C:\\Users\\Admin\\Documents\\Visual Studio 2015\\Projects\\MyProject\\MyProject\\bin\\Debug"
So, By Putting
"\\.."
this, you can go to higher directory.this one "System.IO.Path.GetDirectory(Application.ExecutablePath)" changed to System.IO.Path.GetDirectoryName(Application.ExecutablePath)