如何在.NET控制台应用程序中获取应用程序的路径? [英] How can I get the application's path in a .NET console application?

查看:473
本文介绍了如何在.NET控制台应用程序中获取应用程序的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Windows窗体,我可以使用 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() 位置 < sup> 1

System.Reflection.Assembly.GetExecutingAssembly().Location1

path.getdirectoryname.aspxrel =nofollow noreferrer> System.IO.Path.GetDirectoryName 如果你需要的是目录。

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


1 根据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.

请注意, bitbonk观察 GetExecutingAssembly 返回包含当前正在执行的代码的程序集控制台 .exe 程序集。它可以是由控制台组件从完全不同的位置加载的组件。对于条目程序集,您需要 GetEntryAssembly

Note also that as bitbonk observes, GetExecutingAssembly returns the assembly that contains the code that is currently executing, which may not necessarily be the console .exe assembly. It may be an assembly that has been loaded by the console assembly from a totally different location. For the entry assembly, you need GetEntryAssembly:


在默认应用程序域中获取进程可执行文件。在其他应用程序域中,这是由 AppDomain.ExecuteAssembly 执行的第一个可执行文件。

Gets the process executable in the default application domain. In other application domains, this is the first executable that was executed by AppDomain.ExecuteAssembly.

bitbonk还指出,当程序集在GAC中时,可能不会设置 CodeBase ,因此 AppDomain.CurrentDomain.BaseDirectory 也应该考虑。

bitbonk also notes that CodeBase might not be set when the assembly is in the GAC, so AppDomain.CurrentDomain.BaseDirectory should also be considered.

这篇关于如何在.NET控制台应用程序中获取应用程序的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆