views:

1613

answers:

6

Since the WMI class Win32_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system.

private Boolean is64BitOperatingSystem()
{
RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment");
String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE");
if (processorArchitecture.Equals("x86")) {
return false;
}
else {
return true;
}
}

It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method?

Edit: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.

A: 

If you want to format code, click on the "binary" icon above the data entry text box. That will make your code formatted as "code". You can also put four spaces in the beginning of every line you want to be code and it will be formatted as such.

Dan Herbert
+1  A: 

Looking into the registry is perfectly valid, so long as you can be sure that the user of the application will always have access to what you need.

Greg Hurlman
A: 

@Michael Stum

Sorry, I was trying to fix it while you were fixing it and broke it again. It just doesn't seem to be working out for me.

Jeremy Privett
+3  A: 

Take a look at Raymond Chens solution:

http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx

and here's the PINVOKE for .NET:

http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y

Update: I'd take issue with checking for 'x86'. Who's to say what intel's or AMD's next 32 bit processor may be designated as. The probability is low but it is a risk. You should ask the OS to determine this via the correct API's, not by querying what could be a OS version/platform specific value that may be considered opaque to the outside world. Ask yourself the questions, 1 - is the registry entry concerned properly documented by MS, 2 - If it is do they provide a definitive list of possible values that is guaranteed to permit you as a developer to make the informed decision between whether you are running 32 bit or 64 bit. If the answer is no, then call the API's, yeah it's a but more long winded but it is documented and definitive.

Just my 2c.

Kev
+1  A: 

The easiest way to test for 64-bit under .NET is to check the value of IntPtr.Size.

EDIT: Doh! This will tell you whether or not the current process is 64-bit, not the OS as a whole. Sorry!

Curt Hagenlocher
A: 

The easiest way to test for 64-bit under .NET is to check the value of IntPtr.Size.

I believe the value of IntPtr.Size is 4 for a 32bit app that's running under WOW, isn't it?

Edit: @Edit: Yeah. :)

Jeremy Privett