Reputation: 4104
I'm working on an application that should be able to run 1 of 2 scripts, depending on whether or not the OS running the app is x64 or x86.
Searched around and I came across this thread: How to detect Windows 64-bit platform with .NET?
But apparently my boss is afraid the top answer might not work on all OS' our users will be running (XP/Vista/7). He recommended this code sample:
private void GetCpuDetails(out string cpuType)
{
cpuType = "...";
try
{
using (RegistryKey regKey = Registry.LocalMachine)
{
using (RegistryKey subRegKey = regKey.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"))
{
if (subRegKey.GetValue("ProcessorNameString") != null)
{
cpuType = subRegKey.GetValue("ProcessorNameString").ToString();
}
subRegKey.Close();
}
regKey.Close();
}
}
catch
{
cpuType = "...";
}
}
But I don't understand how you could possibly determine the OS version from the CPU. This seems to be exactly the same conundrum as using PROCESSOR_ARCHITECTURE in that it you'd get 64 or 32 bit based on the CPU, not the OS.
Upvotes: 0
Views: 78
Reputation: 416059
No, it is not possible to determine this from the CPU alone. 64bit CPUs are designed to also run 32bit operating systems, and so knowing what kind of CPU you have is not enough to know what kind of operating system you have.
This is especially true, because nearly all CPUs made in the last several years are 64bit, and it's been this way for long enough now that it's beginning to be unusual (and getting more so all the time) to find 32-bit PCs still in service. However, many PC vendors still ship with 32-bit Windows pre-installed. I wouldn't be surprised to learn that for a purely random sample of PCs, checking the CPU type to learn about the operating system is currently more likely to give you the wrong answer than the right one.
The best method I've seen for detecting the Operating System type is described by Raymond Chen and adpated for C# in this Stack Overflow question, that you have already seen:
That is the correct way to do this for .Net prior to .Net 4.0. For 4.0 and later, you can of course just check System.Environment.Is64BitOperatingSystem
as mentioned in a comment.
Upvotes: 5
Reputation: 463
Why you don't just check IntPtr.Size to determine if your app is running on x64 or x86 mode?
It will mislead you if you are on WoW64, but maybe that could be fine on your scenario?
To clarify: Look in example at Antonijn's response in Load x64 or a x86 DLL depending upon the platform?
Type interop = (IntPtr.Size == 8) ? typeof(Foo64) : typeof(Foo32);
Or at May's response:
(IntPtr.Size == 4) ? "x86" : "x64"
I've used that approach many times.
Upvotes: 1