I started a new project listing the full paths to all running processes. When accessing some of the processes the program crashes and throws a Win32Exception. The description says an error occured while listing the process modules. Initially I thought this problem might occur because I’m running it on a 64-bit platform, so I recompiled it for the CPU types x86 and AnyCPU. I’m getting the same error, though.
Process p = Process.GetProcessById(2011);
string s = proc_by_id.MainModule.FileName;
The error occurs in line #2. The blank fields show processes where the error occured:

Is there any way to get around this error message?
The exception is thrown when you try to access the
MainModuleproperty. The documentation for this property does not listWin32Exceptionas a possible exception, but looking at the IL for the property it is evident that accessing it may throw this exception. In general it will throw this exception if you are trying to do something that is impossible or not allowed in the OS.Win32Exceptionhas the propertyNativeErrorCodeand also aMessagethat will explain what the problem is. You should use that information to troubleshoot your problem.NativeErrorCodeis the Win32 error code. We can guess all day long what the problem is but the only way to actually figure this out is to inspect the error code.But to continue guessing, one source of these exceptions is accessing 64 bit processes from a 32 bit process. Doing that will throw a
Win32Exceptionwith the following message:You can get the number of bits of your process by evaluating
Environment.Is64BitProcess.Even running as a 64 bit process you will never be allowed to access
MainModuleof process 4 (System) or process 0 (System Idle Process). This will throw aWin32Exceptionwith the message:If you problem is that you want to make a process listing similar to the one in Task Manager you will have to handle process 0 and 4 in a special way and give them specific names (just as Task Manager does). Note that on older versions of Windows the system process has ID 8.