在c#中获取已经安装的.NET Framework的最高版本号

我们可以在官网文档中查看所有的版本号

https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed

int rc = 0; // default return code if no .NET Framework is found
System.Collections.Generic.List<string> installedversions = new System.Collections.Generic.List<string>( ); // list of all versions installed
int[] highestversion = new int[] { 0, 0, 0, 0 }; // helper variable to determine which string represents the highest version

using ( Microsoft.Win32.RegistryKey ndpKey =
	Microsoft.Win32.RegistryKey.OpenRemoteBaseKey( Microsoft.Win32.RegistryHive.LocalMachine, "" )
	.OpenSubKey( @"SOFTWARE\Microsoft\NET Framework Setup\NDP\" ) )
{
	foreach ( string versionKeyName in ndpKey.GetSubKeyNames( ) )
	{
		if ( versionKeyName.StartsWith( "v" ) )
		{
			Microsoft.Win32.RegistryKey versionKey = ndpKey.OpenSubKey( versionKeyName );
			string name = (string) versionKey.GetValue( "Version", "" );
			if ( name == "" )
			{
				foreach ( string subKeyName in versionKey.GetSubKeyNames( ) )
				{
					Microsoft.Win32.RegistryKey subKey = versionKey.OpenSubKey( subKeyName );
					name = (string) subKey.GetValue( "Version", "" );
					if ( name != "" )
					{
						installedversions.Add( name );
					}
				}
			}
			else
			{
				installedversions.Add( name );
			}
		}
	}
}
// Determine the highest version
foreach ( string version in installedversions )
{
	int[] version2 = version.Split( ".".ToCharArray( ) ).Select( x => System.Convert.ToInt32( x ) ).ToArray( );
	int minlength = System.Math.Min( version.Length, version2.Length );
	for ( int i = 0; i < minlength; i++ )
	{
		if ( highestversion[i] < System.Convert.ToInt32( version2[i] ) )
		{
			highestversion = version2;
			break;
		}
	}
}
// Write version string to screen
System.Console.WriteLine( string.Join( ".", highestversion.Select( x => x.ToString( ) ).ToArray( ) ) ); // requires System.Linq
// Return code is based on first 2 doirts of highest version
rc = 100 * highestversion[0] + highestversion[1];
return rc;
日期:2020-04-11 22:50:24 来源:oir作者:oir