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.
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
Finding the running application path is as simple as calling Application.ExecutablePath.
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).
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:
- Version using x.GetName().Version,
- Path (similar to Application.ExecutablePath) with x.Location.
- Full assembly name from x.GetName().FullName or just the “short” name with x.GetName().Name.
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.
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.
Try This: create a new windows forms project with containing textbox and add the following code to the main form:
Can you explain the results?