How to determine whether a System.Diagnostics.Process is 32 or 64 bit?
Asked Answered
A

3

8

I tried:

process.MainModule.FileName.Contains("x86")

But it threw an exception for a x64 process:

Win32Exception: Only a part of the ReadProcessMemory ou WriteProcessMemory request finished

Antilebanon answered 26/8, 2010 at 13:55 Comment(5)
You are asking the wrong question. Real question should be: "how did I screw up the ReadProcessMemory call?"Swamy
@Hans I don't care at all about this call as long as the question title is answered. The problem I listed is just a method of answering the title.Antilebanon
possible duplicate of How to know a process is 32-bit or 64-bit programmaticallyKaka
@Jesse the question you pointed asks about the current process, not another process.Antilebanon
look at my answer. It takes into account other processes as the OP wasn't clear.Kaka
D
12

You need to call IsWow64Process via P/Invoke:

[DllImport( "kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi )]
[return: MarshalAs( UnmanagedType.Bool )]
public static extern bool IsWow64Process( [In] IntPtr processHandle, [Out, MarshalAs( UnmanagedType.Bool )] out bool wow64Process );

Here's a helper to make it a bit easier to call:

public static bool Is64BitProcess( this Process process )
{
    if ( !Environment.Is64BitOperatingSystem )
        return false;

    bool isWow64Process;
    if ( !IsWow64Process( process.Handle, out isWow64Process ) )
        throw new Win32Exception( Marshal.GetLastWin32Error() );

    return !isWow64Process;
}
Dakar answered 26/8, 2010 at 15:43 Comment(3)
this method will fail in 32-bit WindowsAntilebanon
On 32-bit Windows all processes are 32-bit, so there's no need to do check. I've edited Is64BitProcess to reflect this.Dakar
Use Process.SafeHandle property to prevent GC cleaning up process.Handle while WinAPI is called.Desirae
C
1

Neither WMI's Win32_Process or System.Diagnostics.Process offer any explicit property.

How about iterating through the loaded modules (Process.Modules), a 32bit process will have loaded %WinDir%\syswow64\kernel32.dll while a 64bit process will have loaded it from %WinDir%\system32\kernel32.dll (this is the one dll that every Windows process loads).

NB. This test will, of course, fail on a x86 OS instance.

Cerotype answered 26/8, 2010 at 15:13 Comment(1)
also fails if running in 32-bit proces while accessing modules of 64-bit process with Win32Exception "A 32 bit processes cannot access modules of a 64 bit process."Ackler
H
1

Environment.Is64BitProcess is probably what you're looking for.

Heather answered 26/8, 2010 at 15:15 Comment(2)
That only tells you if the calling process is 64-bit, I think the OP wants to know if another process is 64-bitDakar
@Phil: Yeah, I wasn't sure what the OP's intent was. I figure he can downvote or comment.Heather

© 2022 - 2024 — McMap. All rights reserved.