How can I get the application's path in a .NET console application?

How do I find the application's path in a console application?

In Windows Forms, I can use Application.StartupPath to find the current path, but this doesn't seem to be available in a console application.


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

Combine that with System.IO.Path.GetDirectoryName if all you want is the directory.

1As per Mr.Mindor's comment:
System.Reflection.Assembly.GetExecutingAssembly().Location returns where the executing assembly is currently located, which may or may not be where the assembly is located when not executing. In the case of shadow copying assemblies, you will get a path in a temp directory. System.Reflection.Assembly.GetExecutingAssembly().CodeBase will return the 'permanent' path of the assembly.


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

AppDomain.CurrentDomain.BaseDirectory

您有两种选择来查找应用程序的目录,您选择的目录取决于您的目的。

// 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);
链接地址: http://www.djcxy.com/p/8924.html

上一篇: 模拟器还是模拟器? 有什么不同?

下一篇: 我如何在.NET控制台应用程序中获取应用程序的路径?