9

Say I have a library, in Nuget, that compiled to netstandard2.0 to support both netcoreapp2.1 and net471.

Now, at compile-time, I don't know if I running under net471, netcoreapp2.1, or netstandard2.0 (I emphasize this because I can't just compile my dll to both netstandard and net471, because if the calling assembly is netstandard2.0, I still don't know what about the entry assembly).

How can I know at runtime which TargetFramwork I running?


I know there is a solution like this:

Assembly.GetEntryAssembly()?
    .GetCustomAttribute<TargetFrameworkAttribute>()?
    .FrameworkName

But if you run this in MSTest and net471, the Assembly.GetEntryAssembly() == null, so I don't want to break tests in projects that uses my Nuget.

Michael
  • 57,169
  • 9
  • 80
  • 125
baruchiro
  • 5,088
  • 5
  • 44
  • 66
  • Have you tried Compiler directives – Prashanth Dec 09 '19 at 07:51
  • See if this answer helps: https://stackoverflow.com/a/51974946/451518 – default locale Dec 09 '19 at 07:53
  • Are you shure that you need to reference to compiler? So, I see you not fully understand the differece of .net standart, .net core and .net framework. So, there are only 2 types of CLR: .net core and .net framework. So, .net standart is only specification, that gives you a confidence that environment are supported a API that you want to use. So, ALL api that specifies in .net standart are suports by .net framework and by .net core. It's created to avoid the code that depends on Framework version. – TemaTre Dec 09 '19 at 07:57
  • 3
    You can use either Environment.Version (will return only the version) or RuntimeInformation.FrameworkDescription (will return version and framework name) – Ruben Martirosyan Dec 09 '19 at 07:57
  • Hi, thanks! Just testing the `FrameworkDescription` and back to here – baruchiro Dec 09 '19 at 07:59

1 Answers1

12

Calling System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription gives you a string:

The strings start with:

".NET" (for .NET 5 and later versions)
".NET Core" (for .NET Core 1.0 - 3.1)
".NET Framework"
".NET Native"`

https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.runtimeinformation.frameworkdescription?view=net-6.0

Dharman
  • 30,962
  • 25
  • 85
  • 135
juFo
  • 17,849
  • 10
  • 105
  • 142