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
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.
This will return the the initial Assembly that references your currentAssembly.
var currentAssembly = Assembly.GetExecutingAssembly();
var callerAssemblies = new StackTrace().GetFrames()
.Select(x => x.GetMethod().ReflectedType.Assembly).Distinct()
.Where(x => x.GetReferencedAssemblies().Any(y => y.FullName == currentAssembly.FullName));
var initialAssembly = callerAssemblies.Last();
It worked for me using this:
System.Reflection.Assembly.GetEntryAssembly().GetName()
Try:
Assembly.GetEntryAssembly().ManifestModule.Name
This should be the assembly that was actually executed to start your process.
This works for getting the original assembly when using two assemblies in an NUnit test, without returning a NULL. Hope this helps.
var currentAssembly = Assembly.GetExecutingAssembly();
var callerAssemblies = new StackTrace().GetFrames()
.Select(x => x.GetMethod().ReflectedType.Assembly).Distinct()
.Where(x => x.GetReferencedAssemblies().Any(y => y.FullName == currentAssembly.FullName));
var initialAssembly = callerAssemblies.Last();
How about Assembly.GetEntryAssembly()? It returns the main executable of the process.
Process.GetCurrentProcess().MainModule.ModuleName
should also return about the same as the ManifestModule name ("yourapp.exe").