如何在控制台应用程序中找到应用程序的路径?

在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。


当前回答

如果你正在寻找一种与。net Core兼容的方法,请使用

System.AppContext.BaseDirectory

这是在。net Framework 4.6和。net Core 1.0(和。net Standard 1.3)中引入的。看到:AppContext。BaseDirectory财产。

根据这一页,

这是。net Core中AppDomain.CurrentDomain.BaseDirectory的首选替代品

其他回答

上面的答案是我需要的90%,但返回了一个Uri,而不是常规路径。

正如在MSDN论坛的帖子中解释的那样,如何将URI路径转换为正常的文件路径?,我使用了以下方法:

// Get normal filepath of this assembly's permanent directory
var path = new Uri(
    System.IO.Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
    ).LocalPath;

试试下面这行简单的代码:

 string exePath = Path.GetDirectoryName( Application.ExecutablePath);

我用过

System.AppDomain.CurrentDomain.BaseDirectory

当我想找到一个相对于应用程序文件夹的路径时。这适用于ASP。Net和winform应用程序。它也不需要任何对System的引用。Web组件。

我将此用于console + net 6

Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)

您可以使用下面的代码来获取当前应用程序目录。

AppDomain.CurrentDomain.BaseDirectory