3

This is a follow up on this answer (and it's comments). What is the difference between getting an executable name from assembly vs process?

System.Reflection.Assembly.GetCallingAssembly.GetEntryAssembly().CodeBase 

vs

Process.GetCurrentProcess().ProcessName

I'm assuming these will be the same all the time? No? Are there pros and cons?

Community
  • 1
  • 1
dev.e.loper
  • 35,446
  • 76
  • 161
  • 247

3 Answers3

6

They're not necessarily the same. Compile these two programs as console applications in the same directory:

// In Test.cs, compile to Test.exe
using System;
using System.Reflection;

public static class Program
{
    static void Main(string[] args)
    {
        AppDomain.CreateDomain("NewDomain").ExecuteAssembly("Test2.exe");
    }
}

// In Test2.cs, compile to Test2.exe
using System;
using System.Diagnostics;
using System.Reflection;

class Test2
{
    static void Main()
    {
        Console.WriteLine("Process: {0}",
                          Process.GetCurrentProcess().ProcessName);
        Console.WriteLine("Entry assembly: {0}", 
                          Assembly.GetEntryAssembly().CodeBase);
    }
}

Output:

Process: Test
Entry assembly: file:///c:/Users/Jon/Test/Test2.EXE
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

ProcessName is the name of the Operating System host process.

Assembly CodeBase points to an assembly inside a given process. The same assembly can be hosted by different processes.

Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
3

No, they needn't return the same values.

As it happens, I ran into this "gotcha" recently: they can return DIFFERENT values depending on whether you're running the .exe directly, or from inside of the MSVS debugger:

How do I get the .exe name of a C# console application?

That's just one example - I'm sure there might be others.

'Hope that helps!

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190