如何在一个.NET控制台应用程序中获得应用程序的路径?

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

Windows Forms中,我可以使用Application.StartupPath来查找当前路径,但在控制台程序中似乎没有这个功能。

解决办法

System.Reflection.Assembly.GetExecutingAssembly().Location 1

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

根据Mr.Mindor的评论: System.Reflection.Assembly.GetExecutingAssembly().Location返回正在执行的程序集的当前位置,这可能是也可能不是程序集在未执行时的位置。在影子复制程序集的情况下,你会得到一个临时目录下的路径。System.Reflection.Assembly.GetExecutingAssembly().CodeBase 将返回汇编的'永久'路径。

评论(18)

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

AppDomain.CurrentDomain.BaseDirectory
评论(6)

你可能正在寻找这样做。

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