如何获取Visual Studio部署项目属性中的TargetPlatform值
解决方案
方法1:运行时直接获取目标平台参数
无需额外配置,代码可直接读取编译/运行时的目标平台信息,和部署项目设置的TargetPlatform一致:
- 快速判断基础平台类型,适配所有.NET版本:
string targetPlatform = Environment.Is64BitProcess ? "x64" : "x86"; // 直接赋值给WinForm控件即可展示 platformLabel.Text = $"程序目标平台:{targetPlatform}";
- 如需获取更详细的编译平台配置(含Any CPU等选项):
using System.Reflection; var assembly = Assembly.GetExecutingAssembly(); assembly.ManifestModule.GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine _); string targetPlatform = peKind switch { PortableExecutableKinds.ILOnly => "Any CPU", PortableExecutableKinds.ILOnly | PortableExecutableKinds.Preferred32Bit => "Any CPU(首选32位)", PortableExecutableKinds.PE32Plus => "x64", PortableExecutableKinds.Required32Bit => "x86", _ => "未知平台" };
方法2:部署时写入注册表后读取
如果需要严格获取部署项目配置的TargetPlatform参数,可通过安装部署的自定义操作实现:
- 打开部署项目的注册表编辑器,在
HKEY_LOCAL_MACHINE\Software\[你的应用厂商名]\[你的应用名]路径下新建字符串值 - 数值名称设为
TargetPlatform,数值数据填写部署项目内置变量[TargetPlatform],打包安装时会自动替换为实际配置的平台值 - WinForm运行时读取注册表值即可,代码示例:
using Microsoft.Win32; string targetPlatform = "未知"; using (var regKey = Registry.LocalMachine.OpenSubKey(@"Software\[你的应用厂商名]\[你的应用名]", false)) { if (regKey != null) { targetPlatform = regKey.GetValue("TargetPlatform", "未知").ToString(); } } platformLabel.Text = $"部署目标平台:{targetPlatform}";
注意:32位程序运行在64位系统时会自动适配注册表
Wow6432Node重定向,无需手动修改路径。
内容的提问来源于stack exchange,提问作者Mehmet Ceylan
相关产品推荐
相关产品推荐

