Comment détecter la plateforme Windows 64 bits avec .NET ?

Comment détecter la plateforme Windows 64 bits avec .NET ?


Source : Stack Overflow [windows]

MISE À JOUR : Comme Joel Coehoorn et d’autres le suggèrent, à partir du .NET Framework 4.0, vous pouvez simplement vérifier Environment.Is64BitOperatingSystem.

IntPtr.Size ne retournera pas la valeur correcte si vous exécutez le .NET Framework 2.0 32 bits sur un Windows 64 bits (il retournerait 32 bits).

Comme le décrit Raymond Chen de Microsoft, vous devez d’abord vérifier si vous exécutez un processus 64 bits (je pense qu’en .NET vous pouvez le faire en vérifiant IntPtr.Size), et si vous exécutez un processus 32 bits, vous devez encore appeler la fonction Win API IsWow64Process. Si celle-ci retourne true, vous exécutez un processus 32 bits sur un Windows 64 bits.

Raymond Chen de Microsoft :
Comment détecter programmatiquement si vous fonctionnez sur un Windows 64 bits

Ma solution :

static bool is64BitProcess = (IntPtr.Size == 8);
static bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process(
    [In] IntPtr hProcess,
    [Out] out bool wow64Process
);

public static bool InternalCheckIsWow64()
{
    if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
        Environment.OSVersion.Version.Major >= 6)
    {
        using (Process p = Process.GetCurrentProcess())
        {
            bool retVal;
            if (!IsWow64Process(p.Handle, out retVal))
            {
                return false;
            }
            return retVal;
        }
    }
    else
    {
        return false;
    }
}