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

后端 未结 2 1237
无人共我
无人共我 2020-12-15 05:36

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

Assembly.GetAssembly(typeof(NUnitTestProject.RGUnitTests)).Location
<
相关标签:
2条回答
  • 2020-12-15 06:15

    It seems rather obvious: When you want the executing assembly, use GetExecutingAssembly.

    Sometimes you don't have one, for example when running as an Office add-in. You could use Assembly.GetAssembly instead.

    0 讨论(0)
  • 2020-12-15 06:19

    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...

    0 讨论(0)
提交回复
热议问题