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?
StartupPath property returns the path for the executable file that started the application, not the path where the application executable is stored. ExecutablePath property returns the path for the executable file that started the application, including the executable name.
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 case Location
will probably be the assembly download cache. CodeBase is not guaranteed to be set for assemblies in the GAC.
UPDATE These days (.NET Core, .NET Standard 1.3+ or .NET Framework 4.6+) it's better to use AppContext.BaseDirectory
rather than AppDomain.CurrentDomain.BaseDirectory
. Both are equivalent, but multiple AppDomains are no longer supported.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With