How to detect Windows 64-bit platform with .NET?

2018-12-31 06:34发布

In a .NET 2.0 C# application I use the following code to detect the operating system platform:

string os_platform = System.Environment.OSVersion.Platform.ToString();

This returns "Win32NT". The problem is that it returns "Win32NT" even when running on Windows Vista 64-bit.

Is there any other method to know the correct platform (32 or 64 bit)?

Note that it should also detect 64 bit when run as a 32 bit application on Windows 64 bit.

29条回答
唯独是你
2楼-- · 2018-12-31 06:46

OSInfo.Bits

using System;
namespace CSharp411
{
    class Program
    {
        static void Main( string[] args )
        {
           Console.WriteLine( "Operation System Information" );
           Console.WriteLine( "----------------------------" );
           Console.WriteLine( "Name = {0}", OSInfo.Name );
           Console.WriteLine( "Edition = {0}", OSInfo.Edition );
           Console.WriteLine( "Service Pack = {0}", OSInfo.ServicePack );
           Console.WriteLine( "Version = {0}", OSInfo.VersionString );
           Console.WriteLine( "Bits = {0}", OSInfo.Bits );
           Console.ReadLine();
        }
    }
}
查看更多
明月照影归
3楼-- · 2018-12-31 06:47

@foobar: You are right, it is too easy ;)

In 99% of the cases, developers with weak system administrator backgrounds ultimately fail to realize the power Microsoft has always provided for anyone to enumerate Windows.

System administrators will always write better and simpler code when it comes to such a point.

Nevertheless, one thing to note, build configuration must be AnyCPU for this environment variable to return the correct values on the correct systems:

System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")

This will return "X86" on 32-bit Windows, and "AMD64" on 64-bit Windows.

查看更多
临风纵饮
4楼-- · 2018-12-31 06:47

All fine, but this should also work from env:

PROCESSOR_ARCHITECTURE=x86

..

PROCESSOR_ARCHITECTURE=AMD64

Too easy, maybe ;-)

查看更多
萌妹纸的霸气范
5楼-- · 2018-12-31 06:48

I use:

Dim drivelet As String = Application.StartupPath.ToString
If Directory.Exists(drivelet(0) & ":\Program Files (x86)") Then
    MsgBox("64bit")
Else
    MsgBox("32bit")
End if

This gets the path where your application is launched in case you have it installed in various places on the computer. Also, you could just do the general C:\ path since 99.9% of computers out there have Windows installed in C:\.

查看更多
伤终究还是伤i
6楼-- · 2018-12-31 06:50

Microsoft has put a code sample for this:

http://1code.codeplex.com/SourceControl/changeset/view/39074#842775

It looks like this:

    /// <summary>
    /// The function determines whether the current operating system is a 
    /// 64-bit operating system.
    /// </summary>
    /// <returns>
    /// The function returns true if the operating system is 64-bit; 
    /// otherwise, it returns false.
    /// </returns>
    public static bool Is64BitOperatingSystem()
    {
        if (IntPtr.Size == 8)  // 64-bit programs run only on Win64
        {
            return true;
        }
        else  // 32-bit programs run on both 32-bit and 64-bit Windows
        {
            // Detect whether the current process is a 32-bit process 
            // running on a 64-bit system.
            bool flag;
            return ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") &&
                IsWow64Process(GetCurrentProcess(), out flag)) && flag);
        }
    }

    /// <summary>
    /// The function determins whether a method exists in the export 
    /// table of a certain module.
    /// </summary>
    /// <param name="moduleName">The name of the module</param>
    /// <param name="methodName">The name of the method</param>
    /// <returns>
    /// The function returns true if the method specified by methodName 
    /// exists in the export table of the module specified by moduleName.
    /// </returns>
    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")]
    static extern IntPtr GetCurrentProcess();

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

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

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);

There is a WMI version available as well (for testing remote machines).

查看更多
刘海飞了
7楼-- · 2018-12-31 06:51

I need to do this, but I also need to be able as an admin do it remotely, either case this seems to work quite nicely for me:

    public static bool is64bit(String host)
    {
        using (var reg = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, host))
        using (var key = reg.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\"))
        {
            return key.GetValue("ProgramFilesDir (x86)") !=null;
        }
    }
查看更多
登录 后发表回答