8

I have a console application (MyProgram.EXE) that references a Utilities assembly.

In my Utilities assembly, I have code that does:

Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim location As String = asm.Location
Dim appName As String = System.IO.Path.GetDirectoryName(location)
Conole.WriteLine("AppName is: {0}", appName)

When I call it from MyProgram.EXE, I receive "AppName is: Utilities.dll"

What I want is "AppName is: MyProgram.EXE"

What am I doing wrong?

5 Answers5

14

Use GetEntryAssembly() instead to get the assembly containing the entry point.

The better way to do it is using System.Environment.CommandLine property instead.

Specifically:

Dim location As String = System.Environment.GetCommandLineArgs()(0)
Dim appName As String = System.IO.Path.GetFileName(location)
Conole.WriteLine("AppName is: {0}", appName)

By the way, you want to use GetFileName instead of GetDirectoryName

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • Why is `System.Environment.CommandLine` better than `GetEntryAssembly()`? – Billy Jo Mar 16 '11 at 20:33
  • Because GetEntryAssembly() can return null. See: http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getentryassembly.aspx – Torben Koch Pløen Oct 02 '12 at 05:56
  • 2
    also (per http://stackoverflow.com/questions/980202/how-do-i-find-the-current-executable-filename): "The GetEntryAssembly method also returns null if you are running a WCF service application in debug mode, under IIS. This is, admittedly, a rare situation that only a developer would encounter. – Gravitas Nov 10 '10 at 10:39" – Abacus Apr 29 '13 at 16:09
12

Since it is VB.NET you were asking about, you can extract this information easily from the 'My' namespace as shown below:

My.Application.Info.AssemblyName
atconway
  • 20,624
  • 30
  • 159
  • 229
3

I use:

CallingAppName = System.Reflection.Assembly.GetEntryAssembly.GetName().Name
1

This is supported all over C#/VB environment.

System.IO.Path.GetFileName(Application.ExecutablePath)
niek tuytel
  • 899
  • 7
  • 18
0

In my case, I didn't have access to My.Application, probably because I was in a global class, so I used:

AppName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
Justin Tolchin
  • 423
  • 5
  • 16