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

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


当前回答

我没有看到任何人将. net Core反射提供的LocalPath转换为可用的系统。IO路径,这是我的版本。

public static string GetApplicationRoot()
{
   var exePath = new Uri(System.Reflection.
   Assembly.GetExecutingAssembly().CodeBase).LocalPath;

   return new FileInfo(exePath).DirectoryName;
       
}

这将返回完整的C:\\xxx\\xxx格式的路径到您的代码所在的位置。

其他回答

对于。net 6,有Environment.ProcessPath。

见https://learn.microsoft.com/en - us/dotnet/api/system.environment.processpath?view=net 6.0

AppDomain.CurrentDomain.BaseDirectory

将解决问题,以引用第三方参考文件与安装包。

我用过

System.AppDomain.CurrentDomain.BaseDirectory

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

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

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

上面的答案是我需要的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;