雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C#教程

當(dāng)前位置:主頁 > 軟件編程 > C#教程 >

C# 使用相同權(quán)限調(diào)用 cmd 傳入命令的方法

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點擊:

本文告訴大家如何使用相同權(quán)限調(diào)用cmd并且傳入命令。

如果想要用相同的權(quán)限運行一個程序,可以使用 ProcessStartInfo 的方法      

 var processStartInfo = new ProcessStartInfo()
   {
    Verb = "runas", // 如果程序是管理員權(quán)限,那么運行 cmd 也是管理員權(quán)限
    FileName = "cmd.exe",
   };

只需要設(shè)置 Verb = "runas" 就可以使用相同的權(quán)限運行程序。

如何設(shè)置程序使用管理員權(quán)限運行,請看

所以需要修改一下在 C# 調(diào)用 ProcessStartInfo 使用 cmd 并且傳入?yún)?shù)的方法    

 var processStartInfo = new ProcessStartInfo()
   {
    Verb = "runas", // 如果程序是管理員權(quán)限,那么運行 cmd 也是管理員權(quán)限
    FileName = "cmd.exe",
    UseShellExecute = false,
    RedirectStandardInput = true,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = false, // 如果需要隱藏窗口,設(shè)置為 true 就不顯示窗口
    StandardOutputEncoding = Encoding.UTF8,
    Arguments = "/K " + str + " &exit",
   };
   var p = Process.Start(processStartInfo);

這里傳入的 Arguments 需要使用 /K 或 /C 放在最前,不然 cmd 不會執(zhí)行參數(shù)。

如果需要拿到輸出就需要用到其他的代碼,所有的代碼請看下面,代碼可以直接復(fù)制使用。

      

 private static (string output, int exitCode) Control(string str)
  {
   var processStartInfo = new ProcessStartInfo()
   {
    Verb = "runas", // 如果程序是管理員權(quán)限,那么運行 cmd 也是管理員權(quán)限
    FileName = "cmd.exe",
    UseShellExecute = false,
    RedirectStandardInput = true,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = false, // 如果需要隱藏窗口,設(shè)置為 true 就不顯示窗口
    StandardOutputEncoding = Encoding.UTF8,
    Arguments = "/K " + str + " &exit",
   };
   var p = Process.Start(processStartInfo);
   //向cmd窗口發(fā)送輸入信息
   p.StandardInput.AutoFlush = true;
   //向標(biāo)準(zhǔn)輸入寫入要執(zhí)行的命令。這里使用&是批處理命令的符號,表示前面一個命令不管是否執(zhí)行成功都執(zhí)行后面(exit)命令,如果不執(zhí)行exit命令,后面調(diào)用ReadToEnd()方法會假死
   //同類的符號還有&&和||前者表示必須前一個命令執(zhí)行成功才會執(zhí)行后面的命令,后者表示必須前一個命令執(zhí)行失敗才會執(zhí)行后面的命令
   //獲取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); //等待程序執(zhí)行完退出進程
   p.Close();
   int ec = 0;
   try
   {
    ec = p.ExitCode;
   }
   catch (Exception)
   {
   }
   return (output + "\r\n", ec);
  }

總結(jié)

以上所述是小編給大家介紹的C# 使用相同權(quán)限調(diào)用 cmd 傳入命令,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!

上一篇:C# WebApi 接口返回值不困惑:返回值類型詳解

欄    目:C#教程

下一篇:C# WebApi CORS跨域問題解決方案

本文標(biāo)題:C# 使用相同權(quán)限調(diào)用 cmd 傳入命令的方法

本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/5142.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有