How do I get the name of the current executable in

2019-01-04 18:32发布

I want to get the name of the currently running program, that is the executable name of the program. In C/C++ you get it from args[0].

20条回答
ら.Afraid
2楼-- · 2019-01-04 18:46

IF you are looking for the full path information of your executable, the reliable way to do it is to use the following:

   var executable = System.Diagnostics.Process.GetCurrentProcess().MainModule
                       .FileName.Replace(".vshost", "");

This eliminates any issues with intermediary dlls, vshost, etc.

查看更多
够拽才男人
3楼-- · 2019-01-04 18:46

Super easy, here:

Environment.CurrentDirectory + "\\" + Process.GetCurrentProcess().ProcessName

查看更多
孤傲高冷的网名
4楼-- · 2019-01-04 18:47

Try Application.ExecutablePath

查看更多
ら.Afraid
5楼-- · 2019-01-04 18:52

You can use Environment.GetCommandLineArgs() to obtain the arguments and Environment.CommandLine to obtain the actual command line as entered.

Also, you can use Assembly.GetEntryAssembly() or Process.GetCurrentProcess().

However, when debugging, you should be careful as this final example may give your debugger's executable name (depending on how you attach the debugger) rather than your executable, as may the other examples.

查看更多
可以哭但决不认输i
6楼-- · 2019-01-04 18:54

System.Diagnostics.Process.GetCurrentProcess() gets the currently running process. You can use the ProcessName property to figure out the name. Below is a sample console app.

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Process.GetCurrentProcess().ProcessName);
        Console.ReadLine();
    }
}
查看更多
聊天终结者
7楼-- · 2019-01-04 18:56

When uncertain or in doubt, run in circles, scream and shout.

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");
    }
}

I can't claim to have tested each option, but it doesn't do anything stupid like returning the vhost during debugging sessions.

查看更多
登录 后发表回答