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

Please indicate which one is best for getting the assembly place.

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

or

 Assembly.GetExecutingAssembly().Location 

Please suggest which one might be better. Can I use GetEntryAssembly() as well?

+7
c # .net-assembly
source share
2 answers

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

myexecutable.exe your code is on myexecutable.exe and you have this script.

trdparty.exe uses Assembly.LoadFile to load the executable and run some code using reflection

myexecutable.exe uses type MyClass

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

So now, if you run your application yourself, you will get this result

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

but if you have the previous script, you get

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

To answer, you must use the one that provides the result you want. The answer may seem obvious that this is Assembly.GetExecutingAssembly() , but sometimes it is not. Imagine that you are trying to load the application.config file associated with the executable .. then the path should most likely be Assembly.GetEntryAssembly().Location to always get its "process" path

as I said, depends on the scenario .. and the goal ...

+18
source share

It seems pretty obvious: if you want to complete the assembly, use GetExecutingAssembly .

Sometimes you don’t have it, for example, when working as an Office add-in. You can use Assembly.GetAssembly instead.

+1
source share

All Articles