views:

281

answers:

5

Hi,

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.

+3  A: 
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

Winston Smith
+2  A: 

Application.ExecutablePath

Application.StartupPath

Tommy Carlier
combined my answer into yours....
Mitch Wheat
+15  A: 

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

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
Tim S. Van Haren
Me too, and having seen the other answers I now feel like I've been missing a trick!
Simon Steele
+1; Should be GetEntryAssembly though.
@weiqure- that's a good point.
RichardOD
A: 

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.

peSHIr
A: 
MessageBox.Show("This program is located in: " + Environment.CurrentDirectory);
baeltazor
Since you were down voted (not by me), you might like to know why. The current directory property can get set in code, so this can change. This can also be different if the application is started from a shortcut.
Kleinux
Thank you for the comment. And the explanation :-)
baeltazor