1

I'm trying to kill some processes by their names (specific names that I already know) In C#. I find them and kill them with Process.Kill(), but sometimes on some processes i get 'access denied'. I assume it is because I'm not running them as an admin. I created a batch that does the same, and if I run it as an admin it kills them all, otherwise not. I can run the batch as an admin via the c# code, i.e:

var psi = new ProcessStartInfo();
psi.Verb = "runas"; //This suppose to run the command as administrator
//Then run a process with this psi

My question is, is this really a way to solve the access problem? Is there a better way? If I run my C# code as an admin, does Process.Kill() suppose to have the same result as doing it with the batch file?

slugster
  • 49,403
  • 14
  • 95
  • 145
Amir B
  • 41
  • 6

1 Answers1

0

What you are talking about are Elevated rights.

You need the programm that finds the programms and sends out the kills to always run Elevated. The most reliable way to do that, is to add this requirement to the Programm Manifest. It is something the UAC will read to help you.

The second most reliable way is to check if you got the rights. And if not, have the programm try to (re)start itself elevated. I did write some sample code for this a while back:

using System;
using System.Diagnostics;
using System.IO;

namespace RunAsAdmin
{
    class Program
    {
        static void Main(string[] args)
        {
            /*Note: Running a batch file (.bat) or similar script file as admin
            Requires starting the interpreter as admin and handing it the file as Parameter 
            See documentation of Interpreting Programm for details */

            //Just getting the Absolute Path for Notepad
            string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
            string FullPath = Path.Combine(windir, @"system32\notepad.exe");

            //The real work part
            //This is the programm to run
            ProcessStartInfo startInfo = new ProcessStartInfo(FullPath);
            //This tells it should run Elevated
            startInfo.Verb = "runas";
            //And that gives the order
            //From here on it should be 100% identical to the Run Dialog (Windows+R), except for the part with the Elevation
            System.Diagnostics.Process.Start(startInfo);
        }
    }
}

Note that regardless how you try to elevate, Eleveation can fail in very rare OS settings.

Christopher
  • 9,634
  • 2
  • 17
  • 31