SSteve
SSteve

Reputation: 10738

What's the preferred way to find the folder my executable is in?

I've inherited a .Net desktop app that has a folder called Data that's in the same folder as the executable. Currently, the app just opens "Data" but that breaks if the current directory is not the directory that contains the executable. I've found two ways of getting the executable's folder: Assembly.GetExecutingAssembly().Location and AppDomain.CurrentDomain.BaseDirectory. The latter is easier to use since I can just append "Data" to the string. Will AppDomain.CurrentDomain.BaseDirectory always return the executable's directory or are there situations where it might not?

Upvotes: 3

Views: 862

Answers (3)

user8686206
user8686206

Reputation:

Maybe this?

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

Upvotes: 1

ggg
ggg

Reputation: 284

There isn't any preferred way, but the most widely used way is this.

System.Reflection.Assembly.GetEntryAssembly().Location;

Upvotes: -1

Bas
Bas

Reputation: 27115

Short answer

Both should be perfectly fine in 99% of cases.

Explanation

The currently executing assembly's directory is a reliable way to get the location of the current executable. Using System.IO, you could simply remove the file name from the path:

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

If the Data folder is shipped as part of a dll file that you compile, you might want to use typeof(SomeClassInMyDll).Assembly.Location instead of the executing assembly. This is to allow for a user of your DLL to have uncommon logic such as loading your assembly based on its path, which might be a different location than the currently executing assembly.

The AppDomain.BaseDirectory property is the location where the currently running code looks for DLL files when it needs to load a dependency. This is generally the same location as the currently executing assembly's path, however, if whoever is calling your code is loading your DLL in a separate AppDomain, again loading it from a file name explicitly, the BaseDirectory might be different from the folder that contains your DLL or executable.

To give an example of that uncommon scenario, let's say there is an executable C:\foo\bar.exe, which dynamically loads a DLL from a different path. This would be done by calling the method Assembly.LoadFrom("C:\MyFolder\MyDll.dll"). In that case, the following would be returned:

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) = C:\foo\
AppDomain.BaseDirectory = C:\foo\
Path.GetDirectoryName(typeof(SomeClassInMyDll).Assembly.Location) = C:\MyFolder\

Upvotes: 3

Related Questions