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

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

问题描述:

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

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

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

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().位置1

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

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

1根据 Mr.Mindor 的评论:
System.Reflection.Assembly.GetExecutingAssembly().Location 返回正在执行的程序集当前所在的位置,这可能是也可能不是该程序集未执行时所在的位置.在卷影复制程序集的情况下,您将在临时目录中获得一个路径.System.Reflection.Assembly.GetExecutingAssembly().CodeBase 将返回程序集的永久"路径.

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.