Wednesday, 27 January 2016

Check if machine is 64 bit or 32 bit in C# ?

We can easily check this by using IntPtr size. If IntPtr.size is 4 then machine running on 32 BIT OS and if it is 8 then machine is 64 BIT OS.
if (IntPtr.Size == 8)
// 64Bit
else
// 32bit
If your program has been build in x86 platform (32 bit) and it is working on 64 bit machine, then you need to add some more checks.
public static bool Is64BitOperatingSystem = (IntPtr.Size == 8) || 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
);

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;
    }
}

Advertisements
Advertisements

No comments:

Post a Comment