代码之家  ›  专栏  ›  技术社区  ›  pistacchio

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

  •  62
  • pistacchio  · 技术社区  · 16 年前

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

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

    事先谢谢。

    7 回复  |  直到 7 年前
        1
  •  124
  •   Sander    16 年前

    我通常通过以下方式访问包含应用程序.exe的目录:

    System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
    
        2
  •  12
  •   Winston Smith    16 年前
    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

        4
  •  4
  •   peSHIr    16 年前

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

    • System.Reflection.Assembly.GetEntryAssembly()
    • typeof(X).Assembly 为班级 X 这是您感兴趣的程序集(对于您可以使用的Windows窗体 typeof(Program) )

    然后获取该程序集所在文件的路径 a 从以下位置加载:

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

    这个 Application Windows窗体应用程序中的对象也是一种可能,如其他答案中所述。

        5
  •  0
  •   dynamiclynk    8 年前

    在努尼特测试时,使用比什尔的答案也很有效。

    var thisType = typeof(MyCustomClass);
    
    var codeLocation = Path.GetDirectoryName(thisType.Assembly.Location);
    
    var codeLocationPath = Path.GetDirectoryName(codeLocation);
    
    var appConfigPath = Path.Combine(codeLocationPath, "AppConfig");
    
        6
  •  0
  •   maks    7 年前

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

    assembly.getentryassembly.location

        7
  •  -3
  •   jay_t55    16 年前
    MessageBox.Show("This program is located in: " + Environment.CurrentDirectory);
    
    推荐文章