How to obtain the framework version of a .NET assembly

If you have ever wondered what version of the .NET framework a given assembly has been built against this post may be of some help.

When working on any application, I have the habit of logging as much information as possible not just about the process but also about the assemblies which the process is referencing and one important part of such information is the version of .NET framework the assembly has been built for e.g. .NET 2, .NET 4.5.1 etc. Note this is different from the run-time version.

The not so accurate

If you look at the assembly object you can find the ImageRuntimeVersion property which gets you the string representation of the CLR saved in the file containing the assembly manifest (which by the way you can view by using a decompiler such as ILSpy or dotPeek) however, this is not accurate as I explain below.

The Problem

The ImageRuntimeVersion property returns either .NET 2.0 or .NET 4.0 regardless of what framework version you have built your assembly against; Meaning that if you have an assembly built in VisualStudio to target .NET 4.5.1, the value returned by the ImageRuntimeVersion is .NET 4.0. Not so helpful is it.

What do we do?

There is "some" hope otherwise why write this article!? Assemblies targeting .NET 4 and above are marked with the TargetFrameworkAttribute which conveniently includes the target framework we are after. This of course means that if your assembly is targeting a framework version less than .NET 4 i.e. .NET 2, 3 and 3.5, then as far as I am aware you are out of luck!

So armed with that knowledge one can obtain the version by calling an extension method such as:

public static string GetFrameworkVersion(this 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");
}

Nima Ara

@NimaAra