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

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


当前回答

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

其他回答

对于控制台应用程序,您可以尝试这样做:

System.IO.Directory.GetCurrentDirectory();

输出(在我的本地机器上):

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug

或者你可以试试(最后有一个额外的反斜杠):

AppDomain.CurrentDomain.BaseDirectory

输出:

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug\

你可能会这样做:

System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)

.Location1 System.Reflection.Assembly.GetExecutingAssembly ()

如果你想要的只是目录,将它与System.IO.Path.GetDirectoryName结合起来。

根据minor先生的评论: System.Reflection.Assembly.GetExecutingAssembly()。Location返回正在执行的程序集当前所在的位置,该位置可能是也可能不是程序集未执行时所在的位置。在阴影复制程序集的情况下,您将获得临时目录中的路径。System.Reflection.Assembly.GetExecutingAssembly()。CodeBase将返回程序集的“永久”路径。

我用过

System.AppDomain.CurrentDomain.BaseDirectory

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

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