I have my project target 4.0. I updated it to 4.5 and VS added
Answering @Dai comment and also addressing the fact that when running as a Windows service, you may not get a prompt to install the specified version in App.config file.
Is there any way to remove it, but reliably enforce a .NET 4.0 vs 4.5 version check in code?
Here is what I use to ensure that the current program is running on a given .NET Framework version, inspired from How do I detect at runtime that .NET version 4.5 is currently running your code?
///
/// Throws an exception if the current version of the .NET Framework is smaller than the specified .
///
/// The minimum supported version of the .NET Framework on which the current program can run.
/// The version to use is not the marketing version, but the file version of mscorlib.dll.
/// See File version history for CLR 4.x and/or .NET Framework Versioni (Build pubblicata) for the version to use.
///
/// The current version of the .NET Framework is smaller than the specified .
/// The version of the .NET Framework on which the current program is running.
public static Version EnsureSupportedDotNetFrameworkVersion(Version supportedVersion)
{
var fileVersion = typeof(int).Assembly.GetCustomAttribute();
var currentVersion = new Version(fileVersion.Version);
if (currentVersion < supportedVersion)
throw new NotSupportedException($"Microsoft .NET Framework {supportedVersion} or newer is required. Current version ({currentVersion}) is not supported.");
return currentVersion;
}
Example usage to ensure running on .NET 4.6.2:
var v462 = new Version(4, 6, 1590, 0);
EnsureSupportedDotNetFrameworkVersion(v462);