C#程序調用cmd.exe執行其他exe進程(並且含多個參數),並把進程結果返回給字符串
阿新 • • 發佈:2017-06-11
() stat syntax || 錯誤 void dia clas ring
1.關鍵代碼部分。
using System.Diagnostics;
|
public class CmdHelper
{
private static string CmdPath = @"C:\Windows\System32\cmd.exe" ;
/// <summary>
/// 執行cmd命令
/// 多命令請使用批處理命令連接符:
/// <![CDATA[
/// &:同時執行兩個命令
/// |:將上一個命令的輸出,作為下一個命令的輸入 /// &&:當&&前的命令成功時,才執行&&後的命令
/// ||:當||前的命令失敗時,才執行||後的命令]]>
/// 其他請百度
/// </summary>
/// <param name="cmd"></param>
/// <param name="output"></param>
public static void RunCmd( string cmd, out string output)
{
cmd = cmd.Trim().TrimEnd( ‘&‘ ) + "&exit" ; //說明:不管命令是否成功均執行exit命令,否則當調用ReadToEnd()方法時,會處於假死狀態
using (Process p = new Process())
{
p.StartInfo.FileName = CmdPath;
p.StartInfo.UseShellExecute = false ; //是否使用操作系統shell啟動
p.StartInfo.RedirectStandardInput = true ; //接受來自調用程序的輸入信息
p.StartInfo.RedirectStandardOutput = true ; //由調用程序獲取輸出信息
p.StartInfo.RedirectStandardError = true ; //重定向標準錯誤輸出
p.StartInfo.CreateNoWindow = true ; //不顯示程序窗口
p.Start(); //啟動程序
//向cmd窗口寫入命令
p.StandardInput.WriteLine(cmd);
p.StandardInput.AutoFlush = true ;
//獲取cmd窗口的輸出信息
output = p.StandardOutput.ReadToEnd();
p.WaitForExit(); //等待程序執行完退出進程
p.Close();
}
}
}
|
使用示例
1:顯示a.txt文件的MD5校驗值給字符串
string cmd = @"fciv.exe -add a.txt" ;
|
C#程序調用cmd.exe執行其他exe進程(並且含多個參數),並把進程結果返回給字符串