我想要获得当前运行程序的名称,即程序的可执行名称。在C/ c++中,你从args[0]中得到它。


当前回答

在。net Core(或Mono)上,当定义进程的二进制文件是Mono或。net Core (dotnet)的运行时二进制文件,而不是您感兴趣的实际应用程序时,大多数答案都不适用。在这种情况下,使用这个:

var myName = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location);

其他回答

这就足够了:

Environment.GetCommandLineArgs()[0];

System.Reflection.Assembly.GetEntryAssembly()。如果程序集没有从内存中加载,Location返回exe名称的位置。 System.Reflection.Assembly.GetEntryAssembly()。CodeBase以URL的形式返回位置。

这是对我有用的代码:

string fullName = Assembly.GetEntryAssembly().Location;
string myName = Path.GetFileNameWithoutExtension(fullName);

上面所有的例子都给了我带有vshost或运行dll名称的processName。

如果您要在。net 6.0或更高版本中发布单文件应用程序,则可以使用Environment。ProcessPath

当你不确定或有疑问时,绕着圈子跑,尖叫和大喊。

class Ourself
{
    public static string OurFileName() {
        System.Reflection.Assembly _objParentAssembly;

        if (System.Reflection.Assembly.GetEntryAssembly() == null)
            _objParentAssembly = System.Reflection.Assembly.GetCallingAssembly();
        else
            _objParentAssembly = System.Reflection.Assembly.GetEntryAssembly();

        if (_objParentAssembly.CodeBase.StartsWith("http://"))
            throw new System.IO.IOException("Deployed from URL");

        if (System.IO.File.Exists(_objParentAssembly.Location))
            return _objParentAssembly.Location;
        if (System.IO.File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName))
            return System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName;
        if (System.IO.File.Exists(System.Reflection.Assembly.GetExecutingAssembly().Location))
            return System.Reflection.Assembly.GetExecutingAssembly().Location;

        throw new System.IO.IOException("Assembly not found");
    }
}

我不能声称已经测试了每个选项,但它不会做任何愚蠢的事情,比如在调试会话期间返回vhost。