如何在C#中以管理员身份运行命令行 [英] How to run command line with admin right in C#
问题描述
我已经引用了其他一些主题,它涉及以下编码,但是它不起作用.我允许它创建命令窗口,并使用"/k"参数使窗口保持打开状态,以便我可以跟踪其输出.
I have referenced some other topics and it comes up the following coding, yet it doesn't work. I allow it creates command window and use "/k" argument keeping the window opened so that I can trace its output.
但是,我可以从窗口中看到警告,该命令需要管理员权限才能执行.如何以管理员权限执行它?
However, I can see the warning from the window that the command needs admin rights to execute. How can I execute it in admin rights?
public void ClearArpCache () {
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/user:Administrator \" cmd /k arp -d \""); // same as "netsh interface ip delete arpcache"
processStartInfo.RedirectStandardOutput = true;
//processStartInfo.CreateNoWindow = true;
//processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.UseShellExecute = false;
processStartInfo.StandardOutputEncoding = Encoding.Default;
processStartInfo.Verb = "runas";
Process.Start (processStartInfo);
UnityEngine.Debug.Log ("ARP table cache cleared.");
}
已
尝试从"cmd.exe"更改为"runas.exe"
Try changing from "cmd.exe" to "runas.exe"
public void ClearArpCache () {
ProcessStartInfo processStartInfo = new ProcessStartInfo("runas.exe", "/user:Administrator \" cmd /k arp -d \""); // same as "netsh interface ip delete arpcache"
processStartInfo.RedirectStandardOutput = true;
//processStartInfo.CreateNoWindow = true;
//processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.UseShellExecute = false;
processStartInfo.StandardOutputEncoding = Encoding.Default;
Process.Start (processStartInfo);
UnityEngine.Debug.Log ("ARP table cache cleared.");
}
推荐答案
仅使用"runas"阐明了失败的原因.为了在 Verb
中使用"runas",必须首先将 UseShellExecute
设置为 true .
Just clarified why it failed using "runas". In order to use "runas" in Verb
, UseShellExecute
must be firstly turned true.
执行以下功能时,它将弹出一个窗口,询问管理员权限,只需单击是"即可开始执行.尽管超出了范围,但如果可能的话,我也想跳过弹出窗口.
When executing following function, it will pop a window asking for admin rights, just click 'Yes' to begin the execution. Though it is beyond the scope, if possible I want to skip the pop-up window as well.
public void ClearArpCache () {
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/k arp -d"); // same as "netsh interface ip delete arpcache"
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.UseShellExecute = true;
processStartInfo.Verb = "runas";
Process.Start (processStartInfo);
UnityEngine.Debug.Log ("ARP table cache cleared.");
}
这篇关于如何在C#中以管理员身份运行命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!