How to find assembly path ,name and version at runtime

nametag Ever needed to find the location of your executable in runtime? what about getting a certain dll name?

Look no further - the following is a quick overview on the .NET objects and functions that can solve your problem.

 

Application.ExecutablePath

System.Windows.Forms.Application has static methods and properties that help manage an application, as well as properties to get information about an application.

What It can do:

Get the path (and name) of the current running application

How:

Finding the running application path is as simple as calling Application.ExecutablePath.

 

GetExecutingAssembly

System.Reflection.Assembly Represents an assembly and can be used to query a certain assembly properties.

What it can do:
Get the path, version and name of a certain assembly (dll or exe).

How:
Assembly.GetExecutingAssembly returns the assembly that contains the code that is currently executing.
Assembly.GetCallingAssembly returns the assembly of the method that invoked the currently executing method.

Notice that there is a difference between the two: in case you run executable A which references assembly B which calls a function foo calling GetCallingAssembly from foo will return assembly A but GetCallingAssembly will return assembly B.

We than get the following:

 

CurrentProcess

The process class which is part of the System.Diagnostics namespace provides access to manage processes and enables you to start and stop local system processes. The function GetCurrentProcess() creates a new Process class and associates it with the current running process.

What It can do:

Name of the running executable.

How:

Process.GetCurrentProcess().ProcessName will return the running process name which is (most of the time) the same name as the executable.

in case of class library (dll) run by another executable you get the executable name.

 

Simple Sample

Try This: create a new windows forms project with containing textbox and add the following code to the main form:

listBox1.Items.Add(Assembly.GetCallingAssembly().Location.ToString());
listBox1.Items.Add(Assembly.GetExecutingAssembly().Location.ToString());
listBox1.Items.Add(Application.ExecutablePath);
listBox1.Items.Add(Process.GetCurrentProcess().ProcessName.ToString());

Can you explain the results?

image

Labels: ,