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,011
  • 72
  • 156
  • 240

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,335,956
  • 823
  • 8,931
  • 9,049
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
  • 123,662
  • 18
  • 237
  • 283
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
  • 107,438
  • 16
  • 129
  • 179