C# Getting Parent Assembly Name of Calling Assembly

Saroop Trivedi picture Saroop Trivedi · Jun 13, 2012 · Viewed 28.5k times · Source

I've got a C# unit test application that I'm working on. There are three assemblies involved - the assembly of the C# app itself, a second assembly that the app uses, and a third assembly that's used by the second one.

So the calls go like this:

First Assembly ------> Second Assembly---------> Third Assembly.

What I need to do in the third assembly is get the name of the Fist Assembly that called the second assembly.

Assembly.GetExecutingAssembly().ManifestModule.Name
Assembly.GetCallingAssembly().ManifestModule.Name

returns the name of the Second assembly. and

Assembly.GetEntryAssembly().ManifestModule.Name

return NULL

Does anybody know if there is a way to get to the assembly name of the First Assembly?

As per the other users demand here I put the code. This is not 100% code but follow of code like this.

namespace FirstAssembly{
public static xcass A
{
        public static Stream OpenResource(string name)
        {
            return Reader.OpenResource(Assembly.GetCallingAssembly(), ".Resources." + name);
        }
}
}

using FirstAssembly;
namespace SecondAssembly{
public static class B 

{
public static Stream FileNameFromType(string Name)

{
return = A.OpenResource(string name);
}
}
}

and Test project method

using SecondAssembly;
namespace ThirdAssembly{
public class TestC
{

 [TestMethod()]
        public void StremSizTest()
        {
            // ARRANGE
            var Stream = B.FileNameFromType("ValidMetaData.xml");
            // ASSERT
            Assert.IsNotNull(Stream , "The Stream  object should not be null.");
        }
}
}

Answer

AVee picture AVee · Jun 21, 2012

I guess you should be able to do it like this:

using System.Diagnostics;
using System.Linq;

...

StackFrame[] frames = new StackTrace().GetFrames();
string initialAssembly = (from f in frames 
                          select f.GetMethod().ReflectedType.AssemblyQualifiedName
                         ).Distinct().Last();

This will get you the Assembly which contains the first method which was started first started in the current thread. So if you're not in the main thread this can be different from the EntryAssembly, if I understand your situation correctly this should be the Assembly your looking for.

You can also get the actual Assembly instead of the name like this:

Assembly initialAssembly = (from f in frames 
                          select f.GetMethod().ReflectedType.Assembly
                         ).Distinct().Last();

Edit - as of Sep. 23rd, 2015

Please, notice that

GetMethod().ReflectedType

can be null, so retrieving its AssemblyQualifiedName could throw an exception. For example, that's interesting if one wants to check a vanilla c.tor dedicated only to an ORM (like linq2db, etc...) POCO class.