1

I am trying to execute the below code to group the running processes by priority and I get a Win32 exception ("Access is denied") at the linq query's group by clause. I ran this code in VS2010 with administrator privilege.

var processesList = Process.GetProcesses();
var processQuerySet = from process in processesList
                      group process by process.PriorityClass into priorityGroup
                      select priorityGroup;           
foreach (var priority in processQuerySet)
{
    Console.WriteLine(priority.Key.ToString());
    foreach (var process in priority)
    {
        Console.WriteLine("\t{0}   {1}", process.ProcessName, process.WorkingSet64);
    }
}
Sam
  • 7,252
  • 16
  • 46
  • 65
Prasanna
  • 187
  • 1
  • 10
  • In general you need administrative privileges to get information about processes owned by other users. However, even running as administrator will not allow you access to the properties of all processes. See http://stackoverflow.com/questions/9501771/how-to-avoid-a-win32-exception-when-accessing-process-mainmodule-filename-in-c – Martin Liversage Jun 29 '14 at 16:05

2 Answers2

2

You can not access PriorityClass of all processes. I would write

ProcessPriorityClass GetPriority(Process p)
{
    try{
        return p.PriorityClass;
    }catch{
        return (ProcessPriorityClass)0;
    }
}

and call it as

group process by GetPriority(process) into priorityGroup
EZI
  • 15,209
  • 2
  • 27
  • 33
2

Some process will throw that exception like "System" and "Idle",its a security design,other times is when your running a 32bit process and trying to access a 64bit,so to avoid those exceptions we will filter out those that have exceptions,1 possible way like this:

Dictionary<string, List<Process>> procs = new Dictionary<string, List<Process>>()
{
    {"With Exception",new List<Process>()},
    {"Without Exception",new List<Process>()}
};

foreach (var proc in Process.GetProcesses())
{
    Exception ex = null;
    try
    {
        //based on your example,many other properties will also throw
        ProcessPriorityClass temp = proc.PriorityClass;
    }
    catch (Exception e)
    {
         ex = e;
    }
    finally
    {
         if (ex == null)
             procs["Without Exception"].Add(proc);
         else
             procs["With Exception"].Add(proc);
    }
}

var processQuerySet = from process in procs["Without Exception"]
                      group process by process.PriorityClass into priorityGroup
                      select priorityGroup;

foreach (var priority in processQuerySet)
{
     Console.WriteLine(priority.Key.ToString());
     foreach (var process in priority)
     {
         Console.WriteLine("\t{0}   {1}", process.ProcessName, process.WorkingSet64);
     }
}

I left things very explicit so you know whats happening.

terrybozzio
  • 4,424
  • 1
  • 19
  • 25