在.NET 2.0 c#应用程序中,我使用以下代码来检测操作系统平台:
string os_platform = System.Environment.OSVersion.Platform.ToString();
返回“Win32NT”。问题是即使在Windows Vista 64位上运行,它也会返回“Win32NT”。
有没有其他方法来知道正确的平台(32位或64位)?
注意,当在Windows 64位上作为32位应用程序运行时,它也应该检测64位。
在.NET 2.0 c#应用程序中,我使用以下代码来检测操作系统平台:
string os_platform = System.Environment.OSVersion.Platform.ToString();
返回“Win32NT”。问题是即使在Windows Vista 64位上运行,它也会返回“Win32NT”。
有没有其他方法来知道正确的平台(32位或64位)?
注意,当在Windows 64位上作为32位应用程序运行时,它也应该检测64位。
当前回答
一切都很好,但这也应该在env中工作:
PROCESSOR_ARCHITECTURE=x86
..
PROCESSOR_ARCHITECTURE=AMD64
可能太简单了;-)
其他回答
这个问题是针对。net 2.0的,但仍然会在谷歌搜索中出现,这里没有人提到,自从。net标准1.1 / .NET核心1.0以来,现在有一个更好的方法来了解CPU架构:
System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture
理论上,这应该能够区分x64和Arm64,尽管我自己没有测试它。
请参见文档。
下面是c#中使用DllImport的直接方法。
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo);
public static bool Is64Bit()
{
bool retVal;
IsWow64Process(Process.GetCurrentProcess().Handle, out retVal);
return retVal;
}
我发现这是检查系统平台和流程的最佳方法:
bool 64BitSystem = Environment.Is64BitOperatingSystem;
bool 64BitProcess = Environment.Is64BitProcess;
第一个属性对于64位系统返回true,对于32位系统返回false。 第二个属性对于64位进程返回true,对于32位进程返回false。
需要这两个属性是因为您可以在64位系统上运行32位进程,因此需要检查系统和进程。
使用dotPeek有助于了解框架是如何实际执行的。考虑到这一点,以下是我的想法:
public static class EnvironmentHelper
{
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")]
static extern IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32")]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll")]
static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
public static bool Is64BitOperatingSystem()
{
// Check if this process is natively an x64 process. If it is, it will only run on x64 environments, thus, the environment must be x64.
if (IntPtr.Size == 8)
return true;
// Check if this process is an x86 process running on an x64 environment.
IntPtr moduleHandle = GetModuleHandle("kernel32");
if (moduleHandle != IntPtr.Zero)
{
IntPtr processAddress = GetProcAddress(moduleHandle, "IsWow64Process");
if (processAddress != IntPtr.Zero)
{
bool result;
if (IsWow64Process(GetCurrentProcess(), out result) && result)
return true;
}
}
// The environment must be an x86 environment.
return false;
}
}
使用示例:
EnvironmentHelper.Is64BitOperatingSystem();
. net 4在环境类中有两个新属性,Is64BitProcess和Is64BitOperatingSystem。有趣的是,如果你使用Reflector,你会发现它们在32位和64位版本的mscorlib中实现的不同。32位版本为Is64BitProcess返回false,并通过P/Invoke为Is64BitOperatingSystem调用IsWow64Process。64位版本对两者都返回true。