title: Kill all processes except those with access is denied error
body: <p>I am trying to create a windows application in C# with the feature that when it runs then all processes except its own gets killed.</p>
  
  <p>I am using the following logic:</p>
  
  <ol>
  <li>Get all the processes and get them stored in a list. </li>
  <li>Create an exception list(list which will have all the process names which are allowed to run). </li>
  <li>Compare all running processes with exception list. if any process other than mentioned are running then it gets killed. </li>
  </ol>
  
  <p>But there are some process which are not allowed to be killed i.e. <code>access is denied</code>
  in that case add those processes to exception list. </p>
  
  <p>But the problem is that this code runs and after sometime screen hangs and application gets closed.</p>
  
  <p>Here is the code</p>
  
  <pre><code>Process[] processlist = Process.GetProcesses();
  string[] recProc = { "winlogon", "VCSExpress", "media player.vshost","VCSExpress", "taskmgr", "smss", "csrss", "wininit", "csrss", "services", 
      "lsass", "lsm", "svchost", "winlogon", "WLTRYSVC", "wlanext", "conhost", "BCMWLTRY", 
      "AvastSvc", "spoolsv", "svchost", "AERTSr64", "btwdins", "NitroPDFDriverService", "NLSSRV32",
      "QDLService2kDell", "dwm", "taskhost", "explorer", "RAVCpl64", "AvastUI", "SearchIndexer", 
      "wmpnetwk", "firefox", "bitlord", "IAStorDataMgrSvc", "LMS", "svchost","media player", 
      "UNS", "regsvr32", "Skype", "OSPPSVC", "audiodg", "NitroPDF", "chrome", "AAM Updates Notifier", 
      "mscorsvw", "media player.vshost", "WmiPrvSE", "conhost", "tasklist","regsvr32","RAVCpl64","idle","dwm","conhost"};
  
  List&lt;string&gt; listOfprocess = new List&lt;string&gt;(recProc);
  
  foreach(Process theprocess in processlist)
  {
      int recProclength = listOfprocess.Count;
      int incrementor;
  
      for (incrementor=0; incrementor &lt; processlist.Length;incrementor++)
      {
          if (theprocess.ProcessName != listOfprocess[incrementor])
          {
              try {
                  theprocess.Kill();
              }
              catch(Win32Exception w){
                  listOfprocess.Add(theprocess.ProcessName);
                  incrementor = 0;
                  break;
              }
          }
      }
  }
  </code></pre>