Process.MainModule & # 8594; "Access is denied"

I want to handle it differently, that is. determine if I have access or not.

Can I find out if you have access to the main module or not?

foreach (Process p in Process.GetProcesses()) { try { //This throws error for some processes. if (p.MainModule.FileName.ToLower().EndsWith(ExeName, StringComparison.CurrentCultureIgnoreCase)) { //Do some stuff } } catch (Exception) { //Acess denied } } 
+7
source share
3 answers

If this happens in Windows 7 or Vista with elevated processes, then you can get the process path directly using win api without denying access to the error.

See links:

Access denied while getting process path

How to get the elevated process path in .Net

+4
source

I see two possible reasons for the exception:

  • Perhaps your process is x86 and the requested process is x64 or vice versa.
  • Each process has a so-called ACL (access control list), which describes who can interact with it, the processes that you encounter have an empty ACL for security reasons, so even an administrator cannot communicate with them. For example, there are several processes (audiodg, System and Idle from the top of my head) that throw an exception due to permissions.

Just use try / catch for your loop to handle these processes.

+3
source
  [Flags] private enum ProcessAccessFlags : uint { QueryLimitedInformation = 0x00001000 } private static extern bool QueryFullProcessImageName( [In] IntPtr hProcess, [In] int dwFlags, [Out] StringBuilder lpExeName, ref int lpdwSize); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr OpenProcess( ProcessAccessFlags processAccess, bool bInheritHandle, int processId); String GetProcessFilename(Process p) { int capacity = 2000; StringBuilder builder = new StringBuilder(capacity); IntPtr ptr = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, p.Id); if (!QueryFullProcessImageName(ptr, 0, builder, ref capacity)) { return String.Empty; } return builder.ToString(); } 

Use pinvoke with ProcessAccessFlags.QueryLimitedInformation . This will allow you to capture the process file name without special administrator privileges and work in x32 and x64 processes.

+1
source