public static string RunCmd(string cmd){ cmd = cmd.Trim().TrimEnd('&') + "&exit";//說明:不管命令是否成功均執行exit命令,否則當調用ReadToEnd()方法時,會處於假死狀態 Process p =new Process(); p.StartInfo.FileName = "cmd.exe"; //p.StartInfo.WorkingDirectory = workingDir; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; //接受來自調用程序的輸入信息 p.StartInfo.RedirectStandardOutput = true; //由調用程序獲取輸出信息 p.StartInfo.RedirectStandardError = true; //重定向標准錯誤輸出 p.StartInfo.CreateNoWindow = true; p.Start(); p.StandardInput.WriteLine(cmd); p.StandardInput.AutoFlush = true; string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); return output; }
