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

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

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

答案

System.Reflection.Assembly.GetExecutingAssembly()Location 1

如果只需要目录,则将其与System.IO.Path.GetDirectoryName结合使用。

1 根据 Mindor 先生的评论:
System.Reflection.Assembly.GetExecutingAssembly().Location返回正在执行的程序集的当前位置,该位置可能不执行时即位于程序集的位置。对于卷影复制程序集,您将在 temp 目录中获得一个路径。 System.Reflection.Assembly.GetExecutingAssembly().CodeBase将返回程序集的 “永久” 路径。

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);
Environment.GetCommandLineArgs()[0];
System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
protected void Application_Start(object sender, EventArgs e)
{
  string p1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  string p2 = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
  string p3 = this.Server.MapPath("");
  Console.WriteLine("p1 = " + p1);
  Console.WriteLine("p2 = " + p2);
  Console.WriteLine("p3 = " + p3);
}
p1 = C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\a897dd66\ec73ff95\assembly\dl3\ff65202d\29daade3_5e84cc01
p2 = C:\inetpub\SBSPortal_staging\
p3 = C:\inetpub\SBSPortal_staging
// 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.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
System.Environment.CurrentDirectory
System.IO.Directory.GetCurrentDirectory();
AppDomain.CurrentDomain.BaseDirectory
System.AppContext.BaseDirectory