通过另一进程杀死管理员的进程

问题描述 投票:1回答:1

我正在尝试通过C#中的名称(我已经知道的特定名称)杀死某些进程。我找到它们并用Process.Kill()杀死它们,但是有时在某些进程上我会“拒绝访问”。我认为这是因为我没有以管理员身份运行它们。我创建了一个执行相同操作的批处理,如果我以管理员身份运行它,则将全部杀死,否则不会。我可以通过c#代码以管理员身份运行该批处理,即:

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

我的问题是,这真的是解决访问问题的方法吗?有没有更好的办法?如果我以管理员身份运行C#代码,Process.Kill()是否应该具有与批处理文件相同的结果?

c# batch-file kill
1个回答
0
投票

您所谈论的是高权限。

您需要找到该程序并发出终止消息的程序,才能始终运行“高架”。最可靠的方法是将此要求添加到Programm Manifest中。 UAC会阅读这些内容以帮助您。

第二种最可靠的方法是检查您是否拥有权利。如果没有,请让程序尝试(重新)启动自身。我确实为此写了一些示例代码:

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);
        }
    }
}

请注意,无论您如何尝试提升,在非常罕见的OS设置中,提升都会失败。

© www.soinside.com 2019 - 2024. All rights reserved.