Share via


How to detect 32 bit or 64 bit compile?

Question

Wednesday, June 18, 2014 1:10 AM

I see there are different connection strings when writing a C# program with ADO.NET (OleDB actually) to dump the contents of a Microsoft Access datagbase table depending on whether you are using /platform:x86 or /platform:x64.

Is there a way to say

#if 64bit

use 64 bit connection string

#else

using 32 bit connection string

#endif

Thanks

Siegfried

siegfried heintze

All replies (3)

Wednesday, June 18, 2014 2:00 AM âś…Answered | 1 vote

You can use Environment.Is64BitProcess (MSDN) to check if the current process is 64-bit or not.

If you want to include/exclude code from the build the you could create new separate build configurations (Build > Configurations) for 32-bit and 64-bit and then use the #if compiler directive to check which configuration you are using.


Wednesday, June 18, 2014 1:18 AM

Hi 

Try this

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

if(InternalCheckIsWow64)
{
//64 bit 
}
else
{
//32 bit
}

Or

if (IntPtr.Size == 4)
{
    // 32-bit
}
else if (IntPtr.Size == 8)
{
    // 64-bit
}
else
{
    // The future is now!
}

References:

http://stackoverflow.com/questions/336633/how-to-detect-windows-64-bit-platform-with-net

http://stackoverflow.com/questions/1953377/how-to-know-a-process-is-32-bit-or-64-bit-programmatically

Mark as answer if you find it use ful

Shridhar J Joshi Thanks a lot


Wednesday, January 24, 2018 5:31 PM

You can use Visual Studio's predefined macros:
https://msdn.microsoft.com/en-us/library/b0084kay.aspx

First, check if _MSC_VER is defined, to ensure it's a Microsoft compiler.

_M_IX86 is defined for x86 processor compilation.
_M_X64 is defined for x64 processor compilation.
_WIN64 is defined for 64-bit processor compilation, and undefined otherwise.

One of these should do what you want.