2

Looking at the following JetBrains dotPeek view of some given assemblies, how can I programmatically determine the platform such assemblies have been compiled against?

I have tried the following method which does not work for assemblies compiled in .NET Core.

public static string GetFrameworkVersion(Assembly assembly)
{
    var targetFrameAttribute = assembly.GetCustomAttributes(true)
        .OfType<TargetFrameworkAttribute>().FirstOrDefault();
    if (targetFrameAttribute == null)
    {
        return ".NET 2, 3 or 3.5";
    }

    return targetFrameAttribute.FrameworkDisplayName.Replace(".NET Framework", ".NET");
}

How is dotPeek able to obtain such details?

enter image description here

MaYaN
  • 6,683
  • 12
  • 57
  • 109
  • possible duplicate of https://stackoverflow.com/questions/19096841/how-to-get-the-version-of-the-net-framework-being-targeted – DOMZE Oct 23 '17 at 20:30
  • It's not a duplicate, the accepted answer on that thread is the code I have already tried which does not work. – MaYaN Oct 23 '17 at 20:31
  • 1
    Your code actually works for .NET Core, just replace `FrameworkDisplayName` with `targetFrameAttribute.FrameworkName`. – Evk Oct 23 '17 at 20:48
  • dotPeek is fairly notorious for guessing at this. https://stackoverflow.com/a/35634257/17034 – Hans Passant Oct 23 '17 at 20:52
  • @Evk It can't work, if you run it against `netstandard.dll` you will realise that `TargetFrameworkAttribute` is not present therefore the code returns `.NET 2, 3 or 3.5` – MaYaN Oct 23 '17 at 20:53
  • @HansPassant agreed but it will be useful if I can at least get what `dotPeek` is displaying for non interop assemblies. They must be reading a header somewhere which I cannot figure out. – MaYaN Oct 23 '17 at 20:56
  • Well I tried with console application compiled for .Net Core 2.0 and this code (witha change I mentioned) returned .NET CoreApp 2.0 – Evk Oct 23 '17 at 20:57
  • Well, keep in mind that what dotPeek reports here is nonsensical. The entire point of .NETStandard is that you can use it to target any platform, not just .NETCore. It probably guesses at it by looking at the version numbers of the reference assemblies. – Hans Passant Oct 23 '17 at 21:02
  • @HansPassant, good point, as @Evk pointed out, it may well be that I am running the code against `netstandard.dll` which is returning null for the attribute. – MaYaN Oct 23 '17 at 21:07

0 Answers0