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


当前回答

为什么没人建议这个,很简单。

Path.GetFileName(Application.ExecutablePath)

其他回答

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

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。

这是你想要的吗?

Assembly.GetExecutingAssembly ().Location

如果你只需要应用程序名而不需要扩展名,这是有效的:

Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName);

System.Diagnostics.Process.GetCurrentProcess()获取当前正在运行的进程。您可以使用ProcessName属性来确定名称。下面是一个示例控制台应用程序。

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Process.GetCurrentProcess().ProcessName);
        Console.ReadLine();
    }
}

这就足够了:

Environment.GetCommandLineArgs()[0];