Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 739
Neeraj Dubey Avatar asked Nov 21 '14 10:11

Neeraj Dubey


People also ask

What is Assembly GetExecutingAssembly ()?

Assembly property to get the currently executing assembly based on a type contained in that assembly. It also calls the GetExecutingAssembly method to show that it returns an Assembly object that represents the same assembly.


Video Answer


1 Answers

It depends on what you want.

  • Assembly.GetAssembly returns the assembly where type is declared.
  • Assembly.GetExecutingAssembly returns the assembly where the current code is being executed on.
  • Assembly.GetEntryAssembly returns the process executable. Keep in mind that this may not be your executable.

For example, imagine your code is on myexecutable.exe.

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 itself, you get this result:

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

but if you have the scenario mentioned above, 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 you want. The answer may seem obvious that it is Assembly.GetExecutingAssembly(), but sometimes it's not. Imagine that you are trying to load the application.config file associated with the executable, then the path will most probably be Assembly.GetEntryAssembly().Location to always get the path of the "process".

As I said, it depends on the scenario and the purpose.

like image 137
CaldasGSM Avatar answered Sep 23 '22 03:09

CaldasGSM