Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process.MainModule --> "Access is denied" [duplicate]

Tags:

c#

process

I want to handle this differently, ie. determine if I have access or not.

Is it possible to see 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 
            }
        }
like image 464
Niklas Avatar asked Dec 08 '11 12:12

Niklas


2 Answers

  [Flags]
  private enum ProcessAccessFlags : uint
  {
      QueryLimitedInformation = 0x00001000
  }

  [DllImport("kernel32.dll", SetLastError = true)]  
  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 grab the filename of the process without having special admin privileges and works across x32 and x64 processes.

like image 192
user99999991 Avatar answered Sep 21 '22 21:09

user99999991


I see two possible causes of the exception:

  1. It may be that your process is x86 and the process being queried is x64 or vice versa.
  2. Every process has a so called ACL (Access control list) that describes who can interact with it, the processes you are having problems with have for security reasons an empty ACL so even as administrator you cannot mess with them. For example, there's a handfull of processes (audiodg, System, and Idle from the top of my head) that throw an exception due to the access rights.

Just use a try/catch to your loop to deal with those processes.

like image 20
Dmitriy Konovalov Avatar answered Sep 22 '22 21:09

Dmitriy Konovalov