Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get application folder path

Tags:

c#

.net

I see that there are some ways to get the application folder path:

  1. Application.StartupPath
  2. System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location)
  3. AppDomain.CurrentDomain.BaseDirectory
  4. System.IO.Directory.GetCurrentDirectory()
  5. Environment.CurrentDirectory
  6. System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
  7. System.IO.Path.GetDirectory(Application.ExecutablePath)

What is the best way depending on the situation?

like image 598
Leo Vo Avatar asked May 18 '11 07:05

Leo Vo


People also ask

What is application StartupPath?

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.


1 Answers

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.

like image 166
Joe Avatar answered Sep 19 '22 11:09

Joe