Check .NET Framework versions
This class has two functions. One gets you the latest version installed. The other one returns a boolean based on whether a specific version is installed or not.
public class NETVersionChecker
{
public struct DOTNETVersionInfo
{
public double FrameworkVersion
public int ServicePack
}
public static bool CheckRequiredDOTNETVersion(DOTNETVersionInfo required)
{
bool reslt = false
double tmpFramework = 0
int tmpSP = 0
try
{
RegistryKey installed_versions = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP", false)
string[] version_names = installed_versions.GetSubKeyNames()
string tmpBaseVersion
foreach (string ver in version_names)
{
tmpFramework = 0
tmpSP = 0
tmpBaseVersion = string.Empty
try
{
string tmpFullVersion = ver.Remove(0, 1)
if (tmpFullVersion.Length > 3)
{
tmpBaseVersion = tmpFullVersion.Remove(tmpFullVersion.IndexOfAny((".").ToCharArray(), 2), tmpFullVersion.Length - 3)
}
else
{
tmpBaseVersion = tmpFullVersion
}
double basicVersion = 0
if (double.TryParse(tmpBaseVersion, out basicVersion))
{
tmpFramework = basicVersion
}
}
catch
{
tmpFramework = 0
}
try
{
tmpSP = Convert.ToInt32(installed_versions.OpenSubKey(ver).GetValue("SP", 0))
}
catch { }
if (tmpFramework == required.FrameworkVersion && tmpSP == required.ServicePack)
{
reslt = true
break
}
}
}
catch (Exception exp)
{
string message = "Error occured:" + exp.Message
if (exp is System.Security.SecurityException)
{
message += "\n Unable to find .NET Framework version. \n The user does not have the permissions required to access the registry key:\n"
+ @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP"
}
MessageBox.Show(message)
}
return reslt
}
public static DOTNETVersionInfo GetLatestDOTNETVersion()
{
DOTNETVersionInfo dnVer
dnVer.FrameworkVersion = 0
dnVer.ServicePack = 0
try
{
RegistryKey installed_versions = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP", false)
string[] version_names = installed_versions.GetSubKeyNames()
double Framework = Convert.ToDouble(version_names[version_names.Length - 1].Remove(0, 1), CultureInfo.InvariantCulture)
dnVer.FrameworkVersion = Framework
int SP = 0
try
{
SP = Convert.ToInt32(installed_versions.OpenSubKey(version_names[version_names.Length - 1]).GetValue("SP", 0))
}
catch { }
dnVer.ServicePack = SP
}
catch(Exception exp)
{
string message = "Error occured:" + exp.Message
if (exp is System.Security.SecurityException)
{
message += "\n Unable to find .NET Framework version. \n The user does not have the permissions required to access the registry key:\n"
+ @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP"
}
MessageBox.Show(message)
}
return dnVer
}
}