判断.Net Framework版本是否满足软件运行需要的版本
不直接运行软件,而是运行一个引导程序,在引导程序里面判断.Net Framework 的版本,满足条件就启动软件,不满足就提示用户安装.Net Framework
下面是如果确定用户的电脑是4.0及以上,才可以使用的新方法,否则只能使用老的方法,一样可以解决
各版本需要的 release 可以在微软官方文档中查到
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/// <summary> /// 判断.Net Framework的Release是否符合需要 /// (.Net Framework 版本在4.0及以上) /// </summary> /// <param name="release">需要的版本 version = 4.5 release = 379893</param> /// <returns></returns> private static bool GetDotNetRelease( int release) { const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\" ; using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey)) { if (ndpKey != null && ndpKey.GetValue( "Release" ) != null ) { return ( int )ndpKey.GetValue( "Release" ) >= release ? true : false ; } return false ; } } |
老的方法,支持2.0及以上
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
/// <summary> /// 判断.Net Framework的Version是否符合需要 /// (.Net Framework 版本在2.0及以上) /// </summary> /// <param name="version">需要的版本 version = 4.5</param> /// <returns></returns> private static bool GetDotNetVersion( string version) { string oldname = "0" ; using (RegistryKey ndpKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "" ). OpenSubKey( @"SOFTWARE\Microsoft\NET Framework Setup\NDP\" )) { foreach ( string versionKeyName in ndpKey.GetSubKeyNames()) { if (versionKeyName.StartsWith( "v" )) { RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName); string newname = ( string )versionKey.GetValue( "Version" , "" ); if ( string .Compare(newname, oldname) > 0) { oldname = newname; } if (newname != "" ) { continue ; } foreach ( string subKeyName in versionKey.GetSubKeyNames()) { RegistryKey subKey = versionKey.OpenSubKey(subKeyName); newname = ( string )subKey.GetValue( "Version" , "" ); if ( string .Compare(newname, oldname) > 0) { oldname = newname; } } } } } return string .Compare(oldname, version) > 0 ? true : false ; } |
最后将判断的代码放在Main方法里
1
2
3
4
5
6
7
8
9
10
11
12
13
|
static void Main( string [] args) { if (!GetDotNetVersion( "4.5" )) { if (MessageBox.Show( "当前缺少运行环境,是否进行安装!\r\n\r\n安装完成后将自动启动软件" , "提示" , MessageBoxButtons.YesNo) == DialogResult.No) return ; Process.Start( @"_framework4.5.2.exe" ).WaitForExit(); //一直等待,直到Framework安装完成 if (GetDotNetVersion( "4.5" )) Process.Start( @"你的程序.exe" ); } else Process.Start( @"你的程序.exe" ); } |
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/sun_zeliang/article/details/81479775