C# Getting Parent Assembly Name of Calling Assembly

前端 未结 9 1303
轮回少年
轮回少年 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:45

    If you know the number of frame in the stack, you can use the StackFrame object and skip the number of previous frame.

    // You skip 2 frames
    System.Diagnostics.StackFrame stack = new System.Diagnostics.StackFrame(2, false);
    string assemblyName = stack.GetMethod().DeclaringType.AssemblyQualifiedName;
    

    But, if you want the first call, you need to get all frames and take the first. (see AVee solution)

    0 讨论(0)
  • 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<Assembly>();
    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);
    }
    
    0 讨论(0)
  • 2021-01-01 09:54

    Assembly.GetEntryAssembly() is null if you run tests from nunit-console too.

    If you just want the name of the executing app then use:

     System.Diagnostics.Process.GetCurrentProcess().ProcessName 
    

    or

     Environment.GetCommandLineArgs()[0];
    

    For nunit-console you would get "nunit-console" and "C:\Program Files\NUnit 2.5.10\bin\net-2.0\nunit-console.exe" respectively.

    0 讨论(0)
提交回复
热议问题