在.NET中获取执行exe路径的最佳方法是什么?

时间:2009-08-03 12:51:35

标签: c# .net filesystems

来自位于c:/ dir的程序a.exe我需要打开文本文件c:/dir/text.txt。我不知道a.exe的位置,但text.txt将始终位于同一路径中。如何从内部获取当前正在执行的程序集的名称到程序本身,以便我可以访问文本文件?

修改: 如果a.exe是Windows服务怎么办?它没有应用程序,因为它不是Windows应用程序。

提前致谢。

7 个答案:

答案 0 :(得分:126)

我经常访问包含我的应用程序的.exe的目录:

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

答案 1 :(得分:12)

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

编辑 - 不使用应用程序对象:

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

有关详细信息,请参阅此处:

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

答案 2 :(得分:4)

答案 3 :(得分:4)

获取您感兴趣的程序集(例如,分配给System.Reflection.Assembly a变量):

  • System.Reflection.Assembly.GetEntryAssembly()
  • typeof(X).Assembly对于您感兴趣的程序集中的X类(对于Windows Forms,您可以使用typeof(Program)

然后获取从中加载程序集a的文件的路径:

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

Windows Forms应用程序中的Application对象也是可能的,如其他答案中所述。

答案 4 :(得分:0)

使用peSHlr的答案在NUnit中进行测试也很有效。

var thisType = typeof(MyCustomClass);

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

var codeLocationPath = Path.GetDirectoryName(codeLocation);

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

答案 5 :(得分:0)

在VB.NET中,我们可以通过以下方式获得它:

Assembly.GetEntryAssembly.Location

答案 6 :(得分:-3)

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