.NET Core 5中如何在运行时获取csproj内定义的最低目标框架
实现方案
方案1:构建时将最低目标版本嵌入程序集(最稳定方案,无需附带.csproj文件)
你之前通过反射拿不到最低目标版本是正常的,默认TargetPlatformMinVersion不会嵌入到程序集元数据中,你可以手动修改项目配置把这个值埋进去:
- 第一步:修改你的.csproj文件,添加如下配置:
<PropertyGroup> <!-- 这里填你要求的最低Windows版本,也就是10.0.19041.0 --> <MinimumWindowsVersion>10.0.19041.0</MinimumWindowsVersion> <!-- 把版本号写入程序集自定义元数据 --> <AssemblyAttribute Include="System.Reflection.AssemblyMetadataAttribute"> <_Parameter1>MinimumWindowsVersion</_Parameter1> <_Parameter2>$(MinimumWindowsVersion)</_Parameter2> </AssemblyAttribute> </PropertyGroup>
- 第二步:运行时用反射读取这个元数据即可,代码示例:
using System.Linq; using System.Reflection; public static Version GetMinimumRequiredWindowsVersion() { var currentAssembly = Assembly.GetExecutingAssembly(); var metaAttribute = currentAssembly.GetCustomAttributes<AssemblyMetadataAttribute>() .FirstOrDefault(attr => attr.Key == "MinimumWindowsVersion"); // 解析失败时返回兜底的最低要求版本 return metaAttribute != null && Version.TryParse(metaAttribute.Value, out var version) ? version : new Version(10, 0, 19041, 0); }
方案2:运行时读取用户当前Windows版本做校验
如果你只需要判断用户系统是否满足要求,可以直接读取系统版本对比,不需要依赖csproj的配置:
// .NET 5+原生支持读取Win10/11的正确内部版本号,无需额外兼容处理 var currentSystemVersion = Environment.OSVersion.Version; var minRequiredVersion = GetMinimumRequiredWindowsVersion(); if (currentSystemVersion < minRequiredVersion) { // 触发系统版本过低的逻辑,比如弹窗提示用户升级 MessageBox.Show("当前系统版本过低,请升级到Windows 10 2004(内部版本19041)及以上版本后运行"); Application.Current.Shutdown(); return; }
注意:不要尝试运行时读取用户设备上的.csproj文件,正式发布后你不会给用户打包源码配置文件,嵌入程序集元数据是最稳妥的实现方式。
内容的提问来源于stack exchange,提问作者batekha
相关产品推荐
相关产品推荐

