【问题标题】:What is the best way to get the executing exe's path in .NET?在 .NET 中获取执行 exe 路径的最佳方法是什么?
【发布时间】:2009-08-03 12:51:34
【问题描述】:

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

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

提前致谢。

【问题讨论】:

    标签: c# .net filesystems


    【解决方案1】:

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

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

    【讨论】:

    • 我也是,看到其他答案后,我现在觉得我错过了一个技巧!
    • 对于那些在 LINQPad 中尝试以上行并获得 NullReferenceException 的人,Assembly.GetEntryAssembly() 在 LINQPad 中返回 null,但在您自己的 .NET 应用程序中它应该返回一个非 null 值。
    • 请注意,如果在 MS 测试中执行此代码将不起作用:在这种情况下,GetEntryAssembly() 返回 null 并且代码会失败。
    • 查看这篇文章以使其在生产和单元测试中工作:codeproject.com/Questions/334267/…
    • 我用Assembly assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();解决单元测试问题
    【解决方案2】:
    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

    【讨论】:

    • 只想指出Application类型位于System.Windows.Forms命名空间——见:msdn.microsoft.com/en-us/library/…
    • WPF 怎么样? , 应用程序不包含 StartupPath 方法??!!
    【解决方案3】:
    【解决方案4】:

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

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

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

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

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

    【讨论】:

      【解决方案5】:

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

      Assembly.GetEntryAssembly.Location
      

      在 C# 中:

      Assembly.GetEntryAssembly().Location
      

      【讨论】:

        【解决方案6】:

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

        var thisType = typeof(MyCustomClass);
        
        var codeLocation = Path.GetDirectoryName(thisType.Assembly.Location);
        
        var codeLocationPath = Path.GetDirectoryName(codeLocation);
        
        var appConfigPath = Path.Combine(codeLocationPath, "AppConfig");
        

        【讨论】:

          【解决方案7】:
          MessageBox.Show("This program is located in: " + Environment.CurrentDirectory);
          

          【讨论】:

          • 既然你被否决了(不是我),你可能想知道为什么。当前目录属性可以在代码中设置,因此可以更改。如果应用程序是从快捷方式启动的,这也可能有所不同。
          • 感谢您的评论。以及解释:-)
          • 对于将来看到此内容的任何人,让我们同意将其保留在这里作为不尝试什么以及为什么不尝试的示例,并且让我们同意至少对 jay 的谦虚回复表示赞同被否决了,因为至少他现在认识到它不起作用的原因。 :)
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-06-13
          • 2010-11-06
          • 2012-10-14
          • 2011-10-26
          • 2011-01-08
          • 2023-03-24
          • 2011-01-30
          相关资源
          最近更新 更多