Which is better for getting assembly location , GetAssembly().Location or GetExecutingAssembly().Location

Neeraj Dubey picture Neeraj Dubey · Nov 21, 2014 · Viewed 9.9k times · Source

Please suggest which is the best to getting executing assembly location.

Assembly.GetAssembly(typeof(NUnitTestProject.RGUnitTests)).Location

or

Assembly.GetExecutingAssembly().Location 

Please suggest which can be better. Can I use GetEntryAssembly() also?

Answer

CaldasGSM picture CaldasGSM · Nov 21, 2014

it depends on what you want.. Assembly.GetAssembly return the assembly where type is declared. Assembly.GetExecutingAssembly returns the assembly where the current code is being executed on. and Assembly.GetEntryAssembly return the process executable, keep in mind that is may not be your executable. ex:

imagine your code is on myexecutable.exe and you have the this scenario.

trdparty.exe -> uses Assembly.LoadFile to load your executable and run some code by reflection

myexecutable.exe -> uses type MyClass

but the trdparty.exe patches your code to use the new version of MyClass located in Patch.dll

So now.. if you run your application all by it self you get this result

Assembly.GetAssembly(typeof(MyClass)) -> myexecutable.exe
Assembly.GetExecutingAssembly() -> myexecutable.exe
Assembly.GetEntryAssembly() -> myexecutable.exe

but if you have the previous scenario you get

Assembly.GetAssembly(typeof(MyClass)) -> Patch.dll
Assembly.GetExecutingAssembly() -> myexecutable.exe
Assembly.GetEntryAssembly() -> trdparty.exe

so as a response you should use the one that provides the result that you want.. the answer may seem obvious that it is Assembly.GetExecutingAssembly() but sometimes is not.. imagine that you are trying to load the application.config file associated with the executable.. then the path will most probably should be Assembly.GetEntryAssembly().Location to always get he path of the "process"

as I said depends on the scenario.. and the purpose...