本文告訴大家如何使用相同權限調用cmd并且傳入命令。
如果想要用相同的權限運行一個程序,可以使用 ProcessStartInfo 的方法
1
2
3
4
5
|
var processStartInfo = new ProcessStartInfo() { Verb = "runas" , // 如果程序是管理員權限,那么運行 cmd 也是管理員權限 FileName = "cmd.exe" , }; |
只需要設置 Verb = "runas" 就可以使用相同的權限運行程序。
如何設置程序使用管理員權限運行,請看
所以需要修改一下在 C# 調用 ProcessStartInfo 使用 cmd 并且傳入參數的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
|
var processStartInfo = new ProcessStartInfo() { Verb = "runas" , // 如果程序是管理員權限,那么運行 cmd 也是管理員權限 FileName = "cmd.exe" , UseShellExecute = false , RedirectStandardInput = true , RedirectStandardOutput = true , RedirectStandardError = true , CreateNoWindow = false , // 如果需要隱藏窗口,設置為 true 就不顯示窗口 StandardOutputEncoding = Encoding.UTF8, Arguments = "/K " + str + " &exit" , }; var p = Process.Start(processStartInfo); |
這里傳入的 Arguments 需要使用 /K 或 /C 放在最前,不然 cmd 不會執行參數。
如果需要拿到輸出就需要用到其他的代碼,所有的代碼請看下面,代碼可以直接復制使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
private static ( string output, int exitCode) Control( string str) { var processStartInfo = new ProcessStartInfo() { Verb = "runas" , // 如果程序是管理員權限,那么運行 cmd 也是管理員權限 FileName = "cmd.exe" , UseShellExecute = false , RedirectStandardInput = true , RedirectStandardOutput = true , RedirectStandardError = true , CreateNoWindow = false , // 如果需要隱藏窗口,設置為 true 就不顯示窗口 StandardOutputEncoding = Encoding.UTF8, Arguments = "/K " + str + " &exit" , }; var p = Process.Start(processStartInfo); //向cmd窗口發送輸入信息 p.StandardInput.AutoFlush = true ; //向標準輸入寫入要執行的命令。這里使用&是批處理命令的符號,表示前面一個命令不管是否執行成功都執行后面(exit)命令,如果不執行exit命令,后面調用ReadToEnd()方法會假死 //同類的符號還有&&和||前者表示必須前一個命令執行成功才會執行后面的命令,后者表示必須前一個命令執行失敗才會執行后面的命令 //獲取cmd窗口的輸出信息 var output = "" ; var task = p.StandardOutput.ReadToEndAsync(); task.Wait(2000); if (task.IsCompleted) { output += task.Result; } task = p.StandardError.ReadToEndAsync(); task.Wait(2000); if (task.IsCompleted) { output += task.Result; } Console.WriteLine(output); p.WaitForExit(10000); //等待程序執行完退出進程 p.Close(); int ec = 0; try { ec = p.ExitCode; } catch (Exception) { } return (output + "\r\n" , ec); } |
總結
以上所述是小編給大家介紹的C# 使用相同權限調用 cmd 傳入命令,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
原文鏈接:https://lindexi.gitee.io/lindexi/post/C