views:

4978

answers:

8

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].

+10  A: 

Try this:

System.Reflection.Assembly.GetExecutingAssembly()

This returns you a System.Reflection.Assembly instance that has all the data you could ever want to know about the current application. I think that the Location property might get what you are after specifically.

Andrew Hare
It might be safer to use `CodeBase` instead of `Location` in case .NET's shadow copy feature is active. See http://blogs.msdn.com/suzcook/archive/2003/06/26/assembly-codebase-vs-assembly-location.aspx
0xA3
+6  A: 

This should suffice:

Environment.GetCommandLineArgs()[0];
James Burgess
Hmm, this returns (when run from vs.net and using the debug hosting thing), the location and name of the filename.vshost.exe ... that is indeed the file that is executing at this time )
Frederik Gheysels
A: 

Is this what you want:

Assembly.GetExecutingAssembly ().Location
Frederik Gheysels
+15  A: 

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();
    }
}
Aaron Daniels
+2  A: 

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.

Jeff Yates
+7  A: 
System.AppDomain.CurrentDomain.FriendlyName
Steven A. Lowe
as opposed to CurrentDomain.ScaryName :)
JustSmith
+2  A: 

System.Reflection.Assembly.GetEntryAssembly().Location returns location of exe name if assembly is not loaded from memory. System.Reflection.Assembly.GetEntryAssembly().CodeBase returns location as URL.

langpavel
A: 

Beware of accepted answer. We've had issues with using System.AppDomain.CurrentDomain.FriendlyName under Click-Once deployed applications. For us, this is returning "DefaultDomain", and not the original exe name.

Gaspode