What is the best way to get the executing exe's path in .NET?

C#.NetFilesystems

C# Problem Overview


From program a.exe located in c:/dir I need to open text file c:/dir/text.txt. I don't know where a.exe could be located, but text.txt will always be in the same path. How to get the name of the currently executing assembly from within to program itself so that i can access the text file?

EDIT: what if a.exe is a Windows service? It doesn't have Application as it is not a Windows Applicaion.

Thanks in advance.

C# Solutions


Solution 1 - C#

I usually access the directory that contains my application's .exe with:

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

Solution 2 - C#

string exePath = Application.ExecutablePath;
string startupPath = Application.StartupPath;

EDIT - Without using application object:

string path = System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );

See here for more info:

http://msdn.microsoft.com/en-us/library/aa457089.aspx

Solution 3 - C#

Solution 4 - C#

Get the assembly you are interested in (eg. assigned to a System.Reflection.Assembly a variable):

  • System.Reflection.Assembly.GetEntryAssembly(), or
  • typeof(X).Assembly for a class X that's in the assembly you're interested in (for Windows Forms you could use typeof(Program))

Then get the path of where the file from which that assembly a was loaded from:

  • System.IO.Path.GetDirectoryName(a.Location)

The Application object from a Windows Forms application is also a possibility, as explained in other answers.

Solution 5 - C#

In VB.NET we can get it in following way:

Assembly.GetEntryAssembly.Location

In C#:

Assembly.GetEntryAssembly().Location

Solution 6 - C#

using peSHlr's answer worked well when testing in NUnit as well.

var thisType = typeof(MyCustomClass);

var codeLocation = Path.GetDirectoryName(thisType.Assembly.Location);

var codeLocationPath = Path.GetDirectoryName(codeLocation);

var appConfigPath = Path.Combine(codeLocationPath, "AppConfig");

Solution 7 - C#

MessageBox.Show("This program is located in: " + Environment.CurrentDirectory);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpistacchioView Question on Stackoverflow
Solution 1 - C#Tim S. Van HarenView Answer on Stackoverflow
Solution 2 - C#Winston SmithView Answer on Stackoverflow
Solution 3 - C#Tommy CarlierView Answer on Stackoverflow
Solution 4 - C#peSHIrView Answer on Stackoverflow
Solution 5 - C#maksView Answer on Stackoverflow
Solution 6 - C#dynamiclynkView Answer on Stackoverflow
Solution 7 - C#jay_t55View Answer on Stackoverflow