1

Using C# reflection to inspect the metadata of an arbitrary .NET DLL, how do I find out if it is written in .NET core (e.g. .NET 6.0 or 7.0) or .NET Framework (e.g. .NET Framework 4.7.2)?

The reason I ask this question, is that I am creating a user interface application used to load existing .NET DLLs, examine them using reflection, and do something.

I have created two versions of this UI, one in .NET core, one in .NET Framework. I intend to let the .NET Core UI to only open DLLs written in .NET core, and the .NET Framework UI to only open DLLs written in .NET Framework. This way I can avoid unexpected strange exceptions due to incompatibility.

For this to happen, when the user uses the .NET Core version of my app to select a DLL written in .NET Framework, I want the app to raise an error message and refues to proceed. Vice versa. This requires my code to tell what the DLL is written in.

  • 1
    Does this answer your question? [How to determine if it is a .net core assembly or a framework assembly with code](https://stackoverflow.com/questions/54057841/how-to-determine-if-it-is-a-net-core-assembly-or-a-framework-assembly-with-code) – thehennyy Jan 31 '23 at 09:12
  • 1
    Assemblies against each .NET Framework versions have some unique patterns (1.0-4.8.x), but that alone is a lengthy answer. .NET Core 1.0-.NET 7/8 is simpler, but still a lengthy post is needed. Even the answers from the linked old threads contain all kinds of misinformation. How accurate an answer do you need? I assume most people might just pick a partial answer and end the discussion. – Lex Li Jan 31 '23 at 09:50
  • 1
    Assemblies aren't written "in" frameworks. They may target specific frameworks; they may not (it's possible to write a "pure" assembly that will load in any version of .NET whatsoever, although it couldn't contain much interesting code). If the question is whether a particular assembly will work for a particular framework (load and/or execute), that's more subtle. – Jeroen Mostert Jan 31 '23 at 11:30

1 Answers1

0

Inspired by this post

tar.FrameworkDisplayName would be your runtime version:

var tar = (TargetFrameworkAttribute)Assembly
    .LoadFrom("yoursAssembly.dll")
    .GetCustomAttributes(typeof(TargetFrameworkAttribute)).First();
Bram
  • 511
  • 1
  • 6
  • 22
  • 1
    You might be surprised that many existing assemblies out there don’t have this attribute. – Lex Li Jan 31 '23 at 09:36
  • 1
    How would that come? Is this attribute only included in the compiled .DLLs that target a newer .NET / .NETFramework version? – Bram Jan 31 '23 at 09:38
  • 2
    There are two decades of C# compilers from Microsoft and other vendors, so you have a lot to learn from. – Lex Li Jan 31 '23 at 09:45