Search code examples
c#.netsystem.reflectionentry-point

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


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

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

This seems like the way to go, but the MSDN reference page for Assembly.GetEntryAssembly states that this method "[c]an return null when called from unmanaged code."

In that case, I would like to know which assembly was called by unmanaged code.

Is there a reliable way of doing this, i.e. one that always returns a non-null Assembly reference?


Solution

  • The best I could think of so far is the following, which should work in a single-threaded scenario:

    // using System.Diagnostics;
    // using System.Linq; 
    Assembly entryAssembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
    

    (The above snippet is optimized for ease of understanding, not for execution speed or memory efficiency.)