Archive

Posts Tagged ‘Determine OS Version’

C# Determine if 64bit or 32bit OS Version

May 14th, 2011 1 comment

I have had an issue where I needed to determine if the executing windows os version was either 32bit or 64bit, and as you can execute a 32bit process on a 64bit system this is a little more difficult then first thought to achieve.

The other condition that this class must have is to execute on all versions of windows and not rely on something that will only execute above a certain version.

After some digging around on google, I found this question on StackOverflow, that went into quite some detail about the different methods that work and will not work. I would suggest a read so you understand the implications of different implementations.

I have settled for a class that has been built around what I found on this question, that will:
1. Determine the os version
2. Run on all versions of windows.

using System;
using System.Runtime.InteropServices;

namespace Testing.Helpers
{
    public static class OsVersionHelper
    {

        // Will return result of 64but OS on all versions of windows that support .net
        public static bool Is64BitOperatingSystem()
        {
            if ( IntPtr.Size == 8 ) //64bit will only run on 64bit
            {
                return true;
            }

            bool flag;
            return (DoesWin32MethodExist("kernel32.dll", "IsWow64Process") && IsWow64Process(GetCurrentProcess(), out flag)) && flag;
        }

        private static bool DoesWin32MethodExist(string moduleName, string methodName)
        {
            IntPtr moduleHandle = GetModuleHandle(moduleName);
            if (moduleHandle == IntPtr.Zero)
            {
                return false;
            }

            return GetProcAddress(moduleHandle, methodName) != IntPtr.Zero;
        }

        [DllImport("kernel32.dll")]
        private static extern IntPtr GetCurrentProcess();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr GetModuleHandle(string moduleName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetProcAddress(IntPtr module, [MarshalAs(UnmanagedType.LPStr)]string procName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool IsWow64Process(IntPtr process, out bool wow64Process);
    }
}
%d bloggers like this: