What happens if I remove the auto added supportedRuntime element?

前端 未结 2 1995
心在旅途
心在旅途 2020-12-07 18:17

I have my project target 4.0. I updated it to 4.5 and VS added


    

        
2条回答
  •  眼角桃花
    2020-12-07 19:00

    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);
    

提交回复
热议问题