LP on .NET

October 21, 2010

Obtaining the Application’s Path and Executable Name

Filed under: .NET,C# — Larry Parker @ 8:09 pm

I came across some code today where the full path and executable name of the application was needed.  It was obtained like this:

String fullPath = Application.ExecutablePath;

The Application class is a Windows Forms class, so the project had a reference to the System.Windows.Forms assembly.

But this particular app was non-visual (it was a Windows service), so the above approach is a bit heavy since the Windows Forms assembly would get loaded into memory and remain there until the app terminated.

A leaner approach is to use the Assembly class found in the System.Reflection namespace.  This is in the mscorlib assembly, which is part of every .NET program.

String fullPath2 = Assembly.GetEntryAssembly().Location;

It’s important to use the GetEntryAssembly method and not GetCallingAssembly or GetExecutingAssembly, since those will not necessarily correspond to the application’s executable.

The only difference I noticed between the value returned by the above two approaches is the casing of the executable’s extension.  Application.ExecutablePath returned <info>.EXE, while Assembly.GetEntryAssembly().Location returned <info>.exe.  Aside from that the casing was the same.

Hope this helps.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog at WordPress.com.

%d bloggers like this: