C#靜默執行CMD命令的方法
當前位置:點晴教程→知識管理交流
→『 技術文檔交流 』
/// <summary>
/// 執行CMD命令
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ExeCmd(string str)
{
try
{
//string str = Console.ReadLine();
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
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(str + "&exit");
p.StandardInput.AutoFlush = true;
//p.StandardInput.WriteLine("exit");
//向標準輸入寫入要執行的命令。這里使用&是批處理命令的符號,表示前面一個命令不管是否執行成功都執行后面(exit)命令,如果不執行exit命令,后面調用ReadToEnd()方法會假死
//同類的符號還有&&和||前者表示必須前一個命令執行成功才會執行后面的命令,后者表示必須前一個命令執行失敗才會執行后面的命令
//獲取cmd窗口的輸出信息
string output = p.StandardOutput.ReadToEnd();
//StreamReader reader = p.StandardOutput;
//string line=reader.ReadLine();
//while (!reader.EndOfStream)
//{
// str += line + " ";
// line = reader.ReadLine();
//}
p.WaitForExit();//等待程序執行完退出進程
p.Close();
Console.WriteLine(output);
return output;
}
catch (Exception ex)
{
return null;
}
}
該文章在 2021/3/15 14:39:21 編輯過 |
關鍵字查詢
相關文章
正在查詢... |