我想检查用户正在运行的CPU架构,是i386还是X64或AMD64.我想用C#做.我知道我可以尝试WMI或注册表.除了这两个之外还有其他方式吗?我的项目面向.NET 2.0!
你也可以试试(只有在没有被操纵的情况下才有效):
System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")
我在这里得到的是检查32对64位操作系统.评分最高的答案是查看当前流程的设置.找不到答案后,我找到了以下设置.希望这对你有用.
bool is64 = System.Environment.Is64BitOperatingSystem
这是一段似乎有用的代码(基于P/Invoke):
public static ProcessorArchitecture GetProcessorArchitecture() { SYSTEM_INFO si = new SYSTEM_INFO(); GetNativeSystemInfo(ref si); switch (si.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_AMD64: return ProcessorArchitecture.Amd64; case PROCESSOR_ARCHITECTURE_IA64: return ProcessorArchitecture.IA64; case PROCESSOR_ARCHITECTURE_INTEL: return ProcessorArchitecture.X86; default: return ProcessorArchitecture.None; // that's weird :-) } }
同
[DllImport("kernel32.dll")] private static extern void GetNativeSystemInfo(ref SYSTEM_INFO lpSystemInfo); private const int PROCESSOR_ARCHITECTURE_AMD64 = 9; private const int PROCESSOR_ARCHITECTURE_IA64 = 6; private const int PROCESSOR_ARCHITECTURE_INTEL = 0; [StructLayout(LayoutKind.Sequential)] private struct SYSTEM_INFO { public short wProcessorArchitecture; public short wReserved; public int dwPageSize; public IntPtr lpMinimumApplicationAddress; public IntPtr lpMaximumApplicationAddress; public IntPtr dwActiveProcessorMask; public int dwNumberOfProcessors; public int dwProcessorType; public int dwAllocationGranularity; public short wProcessorLevel; public short wProcessorRevision; }
请注意,此代码重用现有CLR的ProcessorArchitecture枚举,并支持.NET framework 2及更高版本.
Win32_Processor WMI类将完成这项工作.使用MgmtClassGen.exe生成强类型包装器.
最后,解决C#中当前运行的CLR运行时的平台/处理器架构的最短技巧是:
PortableExecutableKinds peKind; ImageFileMachine machine; typeof(object).Module.GetPEKind(out peKind, out machine);
这里Module.GetPEKind返回一个ImageFileMachine枚举,它存在于.NET v2之后:
public enum ImageFileMachine { I386 = 0x014C, IA64 = 0x0200, AMD64 = 0x8664, ARM = 0x01C4 // new in .NET 4.5 }
为什么不使用new AssemblyName(fullName)
或typeof(object).Assembly.GetName()
?
那么HACK
在ASP.NET MVC源代码中有这个注释(从1.0开始):
private static string GetMvcVersionString() { // DevDiv 216459: // This code originally used Assembly.GetName(), but that requires FileIOPermission, which isn't granted in // medium trust. However, Assembly.FullName *is* accessible in medium trust. return new AssemblyName(typeof(MvcHttpHandler).Assembly.FullName).Version.ToString(2); }
看到他们为自己使用一些隐藏的技巧.遗憾的是,AssemblyName
构造函数没有ProcessorArchitecture
适当地设置字段,它只None
适用于任何新的AssemblyName.
因此,对于未来的读者,我建议您使用带有ImageFileMachine的丑陋的GetPEKind!
笔记:
这将返回当前运行的运行时体系结构,而不是底层系统体系结
也就是说,唯一的例外是I386运行时可能在AMD64系统上运行.
在mono/ubuntu 14.04/AMD64和.NET/Win7/I386上测试.