I need an alternative to `Assembly.GetEntryAssembly()` that never returns null

前端 未结 3 2040
时光取名叫无心
时光取名叫无心 2020-12-10 11:21

I need to find the assembly in which managed code execution started.

// using System.Reflection;
Assembly entryAssembly = Assembly.GetEntryAssembly();
         


        
3条回答
  •  死守一世寂寞
    2020-12-10 11:30

    Another (largely untested) starting point for a working solution might be something like this:

    // using System;
    // using System.Diagnostics;
    // using System.Linq;
    ProcessModule mainModule = Process.GetCurrentProcess().MainModule;
    Assembly entryAssembly = AppDomain.CurrentDomain.GetAssemblies()
                             .Single(assembly => assembly.Location == mainModule.FileName);
    

    Some uncertainties remain:

    • Modules and assemblies are not the same thing. ProcessModule might even be conceptually different from Module. Would the above code always work in the presence of multi-module (i.e. multi-file) assemblies, especially when an assembly's entry point is not in the manifest module?

    • Is Process.MainModule guaranteed to always returns a non-null reference?

提交回复
热议问题