C# Getting Parent Assembly Name of Calling Assembly

前端 未结 9 1377
轮回少年
轮回少年 2021-01-01 09:02

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

9条回答
  •  不知归路
    2021-01-01 09:53

    Not completely sure what you're looking for, especially as when running in the context of a unit test you'll wind up with:

    mscorlib.dll
    Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll
    

    (or something similar depending on your test runner) in the set of assemblies that lead to any method being called.

    The below code prints the names of each of the assemblies involved in the call.

    var trace = new StackTrace();
    var assemblies = new List();
    var frames = trace.GetFrames();
    
    if(frames == null)
    {
        throw new Exception("Couldn't get the stack trace");
    }
    
    foreach(var frame in frames)
    {
        var method = frame.GetMethod();
        var declaringType = method.DeclaringType;
    
        if(declaringType == null)
        {
            continue;
        }
    
        var assembly = declaringType.Assembly;
        var lastAssembly = assemblies.LastOrDefault();
    
        if(assembly != lastAssembly)
        {
            assemblies.Add(assembly);
        }
    }
    
    foreach(var assembly in assemblies)
    {
        Debug.WriteLine(assembly.ManifestModule.Name);
    }
    

提交回复
热议问题