baruchiro
baruchiro

Reputation: 5801

How to know if I running under .NET Framework or .NET Core

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.

Upvotes: 11

Views: 4244

Answers (1)

juFo
juFo

Reputation: 18567

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

Upvotes: 13

Related Questions