【问题标题】:Getting the absolute path of the executable, using C#?使用 C# 获取可执行文件的绝对路径?
【发布时间】:2010-12-12 03:00:50
【问题描述】:

看看这个伪代码:

string exe_path = system.get_exe_path()
print "This executable is located in " + exe_path

如果我构建上述程序并将可执行文件放在C:/meow/ 中,它会在每次运行时打印出This executable is located in C:/meow/,无论当前工作目录如何。

如何使用C# 轻松完成此任务?

【问题讨论】:

标签: c# directory executable


【解决方案1】:

MSDN has an article 表示使用System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;如果您需要该目录,请在该结果上使用System.IO.Path.GetDirectoryName

或者,有更短的Application.ExecutablePath,它“获取启动应用程序的可执行文件的路径,包括可执行文件名称”,这可能意味着它的可靠性稍差,具体取决于应用程序的启动方式。

【讨论】:

  • System.Reflection.Assembly.GetExecutingAssembly() 只会在调用它的地方获取 EXE 程序集。 GetEntryAssembly() 将获得正确的程序集。
  • 如果您创建 Windows 服务,这一点尤其重要,因为该服务是从 C:\Windows\System32 启动的,因此您将拥有该工作目录。我将改用 GraemeF 的方法。
  • 上述方法将当前路径作为 URI 返回(即“file://c:\\data”)。有用的是:System.Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location ) );
  • 实际上是“System.IO.Path”。因此,具有正确命名空间的完全限定名称应该是:System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
  • noelicus:根据答案和 cmets,几乎总是能正常工作的安全准确的方法是:System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location )
【解决方案2】:
AppDomain.CurrentDomain.BaseDirectory

【讨论】:

  • 这是最好、最简单的答案。此方法适用于 linux/mono 和 Windows,与当前目录无关。
【解决方案3】:
using System.Reflection;

string myExeDir = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.ToString();

【讨论】:

  • 不错,不过可以简化为System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),也更快。
【解决方案4】:
var dir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

我跳入评分最高的答案,但发现自己没有得到预期的结果。我必须阅读 cmets 才能找到我想要的东西。

出于这个原因,我发布了 cmets 中列出的答案,以给予它应得的曝光率。

【讨论】:

  • 很好,虽然应该是.GetEntryAssembly(),而不是.GetExecutingAssembly()
【解决方案5】:

“获取包含清单的已加载文件的路径或 UNC 位置。”

见:http://msdn.microsoft.com/en-us/library/system.reflection.assembly.location.aspx

Application.ResourceAssembly.Location

【讨论】:

  • 请注意,此解决方案是特定于 WPF 的:“Application 是一个封装 WPF 应用程序特定功能的类”。
【解决方案6】:

假设我在控制台应用程序中有 .config 文件,现在如下所示。

Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\YourFolderName\\log4net.config";

【讨论】:

  • CurrentDirectory 不能保证是应用程序正在执行的目录。
  • 请使用Path.Combine。有很多代码不能通过像这样的手动组合路径在 Mono 中正常工作。
【解决方案7】:

在我这边,我使用了一个表单应用程序:

String Directory = System.Windows.Forms.Application.StartupPath;

它采用应用程序启动路径。

【讨论】:

    【解决方案8】:

    对我有用但不在上面的是Process.GetCurrentProcess().MainModule.FileName

    【讨论】:

      【解决方案9】:

      如果您打算构建一个与任务计划程序一起使用的控制台应用程序,我建议您使用这种方法:

      var execDirectoryPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)?.Replace("file:\\", "");
      

      这样,路径将适应您放置可执行文件的任何位置。

      【讨论】:

        猜你喜欢
        • 2012-05-10
        • 1970-01-01
        • 2022-01-14
        • 2012-04-24
        • 2010-09-18
        • 2016-11-19
        • 1970-01-01
        相关资源
        最近更新 更多