What is the best way to get executable exe path in .NET?

From the a.exe program located in c: / dir, I need to open the text file c: /dir/text.txt. I do not know where the a.exe file can be located, but text.txt will always be the same path. How to get the name of the current executable assembly from the inside for the program itself so that I can access the text file?

EDIT : what if a.exe is a Windows service? It does not have an application because it is not a Windows application.

Thanks in advance.

+64
c # filesystems
Aug 03 '09 at 12:51
source share
7 answers

I usually refer to the directory that contains my .exe application with:

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); 
+128
Aug 03 '09 at 12:54
source share
 string exePath = Application.ExecutablePath; string startupPath = Application.StartupPath; 

EDIT - Without using the application object:

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

See here for more details:

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

+12
Aug 03 '09 at 12:54
source share
+4
Aug 03 '09 at 12:54
source share

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

  • System.Reflection.Assembly.GetEntryAssembly() , or
  • typeof(X).Assembly for class X , which is in the assembly you are interested in (for Windows Forms, you can use typeof(Program) )

Then enter the path from which the file from which this assembly a was loaded was downloaded:

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

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

+4
Aug 03 '09 at 13:14
source share

In VB.NET, we can get this as follows:

 Assembly.GetEntryAssembly.Location 

In C #:

 Assembly.GetEntryAssembly().Location 
+1
May 7 '18 at 7:12
source share

using peSHlr answer, worked well when testing in NUnit.

 var thisType = typeof(MyCustomClass); var codeLocation = Path.GetDirectoryName(thisType.Assembly.Location); var codeLocationPath = Path.GetDirectoryName(codeLocation); var appConfigPath = Path.Combine(codeLocationPath, "AppConfig"); 
0
Mar 16 '17 at 19:55
source share
 MessageBox.Show("This program is located in: " + Environment.CurrentDirectory); 
-3
Aug 07 '09 at 19:02
source share



All Articles