How to run command line with admin right in C# [duplicate]

巧了我就是萌 提交于 2020-12-13 07:51:44

问题


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

EDITED:

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

回答1:


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


来源:https://stackoverflow.com/questions/45813861/how-to-run-command-line-with-admin-right-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!