[.NET]如何判斷OS是x86 or x64

[.NET]如何判斷OS是x86 or x64

今天程式需要判斷OS是x86 or x64來決定寫到不同位置的機碼,所以就把討論區(How to check whether the system is 32 bit or 64 bit ?)的訊息記錄下來。

Tergiver提供的方式如下,


public static bool Is64BitProcess
{
    get { return IntPtr.Size == 8; }
}

public static bool Is64BitOperatingSystem
{
    get
    {
        // Clearly if this is a 64-bit process we must be on a 64-bit OS.
        if (Is64BitProcess)
            return true;
        // Ok, so we are a 32-bit process, but is the OS 64-bit?
        // If we are running under Wow64 than the OS is 64-bit.
        bool isWow64;
        return ModuleContainsFunction("kernel32.dll", "IsWow64Process") && IsWow64Process(GetCurrentProcess(), out isWow64) && isWow64;
    }
}


static bool ModuleContainsFunction(string moduleName, string methodName)
{
    IntPtr hModule = GetModuleHandle(moduleName);
    if (hModule != IntPtr.Zero)
        return GetProcAddress(hModule, methodName) != IntPtr.Zero;
    return false;
}

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
extern static bool IsWow64Process(IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] out bool isWow64);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
extern static IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
extern static IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
extern static IntPtr GetProcAddress(IntPtr hModule, string methodName);

 

當然,如果是使用.NET 4以上的話(.NET 4, .NET 4.5),直接用Environment的Is64BitOperatingSystem屬性就可以了!

Environment.Is64BitOperatingSystem Property

Environment.Is64BitProcess Property

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^