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

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


当前回答

您有两个选项来查找应用程序的目录,具体选择哪个取决于您的目的。

// to get the location the assembly is executing from
//(not necessarily where the it normally resides on disk)
// in the case of the using shadow copies, for instance in NUnit tests, 
// this will be in a temp directory.
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;

//To get the location the assembly normally resides on disk or the install directory
string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

//once you have the path you get the directory with:
var directory = System.IO.Path.GetDirectoryName(path);

其他回答

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

AppDomain.CurrentDomain.BaseDirectory

你可能会这样做:

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

你可以简单地添加到你的项目引用System.Windows.Forms,然后像往常一样使用System.Windows.Forms. application . startuppath。

因此,不需要更复杂的方法或使用反射。

AppDomain.CurrentDomain.BaseDirectory

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

对于。net 6,有Environment.ProcessPath。

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