13

A .NET dll can be run as both 32 bit and 64 bit on a machine with an x64 processor. I need to determine at runtime what bitness my application is running under.

Currently I've been doing something like System.IntPtr.Size == 8, but that seems like an ugly hack. Is there a more "correct" way of determining this?

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552

3 Answers3

26

In .NET 4 and beyond, including .NET Core, the System.Environment class has two static properties: Is64BitOperatingSystem and Is64BitProcess. In earlier .NET versions you need to use the IntPtr size approach.

Richard
  • 106,783
  • 21
  • 203
  • 265
  • You also need to check if the process is running under WOW64 in .NET versions previous to 4. Just checking the size of the pointer isn't sufficient. – George Howarth Jul 23 '10 at 14:59
  • @George: I don't want the bitness of the OS, I want the bitness my code is using. Therefore what Richard describes is right. Checking this answer because it has the most upvotes; unfortunately I cannot use .NET 4 :( – Billy ONeal Jul 23 '10 at 15:17
  • Ummm, surely the accepted answer is the correct one, not the one with the most upvotes that is, as you even admit, incorrect for your situation... – Adam Houldsworth Jul 23 '10 at 15:28
  • @Adam: When there is no "correct" answer for my situation posted, then one should pick the best of the remaining alternatives. – Billy ONeal Jul 23 '10 at 21:07
  • @Billy actually you can answer the post yourself to provide the correct answer and mark it as accepted - you'll even get a badge for it I think :-) – Adam Houldsworth Jul 24 '10 at 12:20
6

Pre .NET 4 it was suggested to use the size of an IntPtr (4 for 32 bit and 8 for 64 bit). However, this doesn't give you the bitness of the machine - it gives you the bitness of the CLR that is being used.

That is an important difference if you are running inside a 32 bit process, such as application add-ins. I've got a blog post about finding the machines bitness based on WMI:

http://adamhouldsworth.blogspot.com/2010/03/64bit-registry-from-32bit-application.html

Note however, that I'm still unclear if this will truely represent the current OS bitness (as it's using the processor).

For the vast majority of situations, under normal compilation (AnyCPU) running your own app, IntPtr will suffice.

In .NET 4, as others have said, there is now Environment.Is64BitProcess and Environment.Is64BitOperatingSystem.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
1

In .Net 4.0 you can use

Environment.Is64BitProcess and
Environment.Is64BitOperatingSystem
Toan Nguyen
  • 11,263
  • 5
  • 43
  • 59