Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...