using System; using System.Diagnostics; namespace Business { /// <summary> /// Command 的摘要說明。 /// </summary> public class Command { private Process proc = null; /// <summary> /// 構造方法 /// </summary> public Command() { proc = new Process(); } /// <summary> /// 執行CMD語句 /// </summary> /// <param name="cmd">要執行的CMD命令</param> public void RunCmd(string cmd) { proc.StartInfo.CreateNoWindow = true; proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); proc.StandardInput.WriteLine(cmd); proc.Close(); } /// <summary> /// 打開軟件並執行命令 /// </summary> /// <param name="programName">軟件路徑加名稱(.exe文件)</param> /// <param name="cmd">要執行的命令</param> public void RunProgram(string programName,string cmd) { System.Diagnosties.Process p=new System.Diagnosties.Process(); p.StartInfo.FileName="cmd.exe";//要執行的程序名稱 p.StartInfo.UseShellExecute=false; p.StartInfo.RedirectStanderInput=true;//可能接受來自調用程序的輸入信息 p.StartInfo.RedirectStanderOutput=true;//由調用程序獲取輸出信息 p.StartInfo.CreateNoWindow=true;//不顯示程序窗口 p.Start();//啟動程序 //向CMD窗口發送輸入信息: p.StanderInput.WriteLine("shutdown -r t 10"); //10秒后重啟(C#中可不好做哦) //獲取CMD窗口的輸出信息: string sOutput = p.StandardOutput.ReadToEnd();有啦以下代碼,就可以神不知鬼不覺的操作CMD啦。總之,Process類是一個非常有用的類,它十分方便的利用第三方的程序擴展了C#的功能。 if (cmd.Length != 0) { proc.StandardInput.WriteLine(cmd); } proc.Close(); } /// <summary> /// 打開軟件 /// </summary> /// <param name="programName">軟件路徑加名稱(.exe文件)</param> public void RunProgram(string programName) { this.RunProgram(programName,""); } } }
調用時
Command cmd = new Command(); cmd.RunCmd("dir");
獲取輸出信息應注意:
ReadtoEnd()容易卡住:
string outStr = proc.StandardOutput.ReadtoEnd();
更傾向於使用ReadLine():
[csharp] view plaincopyprint?string tmptStr = proc.StandardOutput.ReadLine(); string outStr = ""; while (tmptStr != "") { outStr += outStr; tmptStr = proc.StandardOutput.ReadLine(); }
調用第三方exe時可以使用如下:
/// <summary> /// 執行ThermSpy.exe /// </summary> private void CmdThermSpy() { Process p = new Process(); p.StartInfo.WorkingDirectory = Environment.CurrentDirectory; p.StartInfo.FileName = "ThermSpyPremium.exe"; p.StartInfo.Arguments = "-header:gpu -datetime -log:NV_clock.log"; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); }
