【问题标题】:Killing process as admin via another process通过另一个进程以管理员身份杀死进程
【发布时间】:2019-11-06 21:48:06
【问题描述】:

我试图在 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】:

    您所说的是提升权限。

    您需要找到程序并发出杀戮的程序以始终运行 Elevated。最可靠的方法是将此要求添加到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);
            }
        }
    }
    

    请注意,无论您如何尝试提升,提升都可能在非常罕见的操作系统设置中失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 2021-11-29
      相关资源
      最近更新 更多