Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...