private string ExecuteCmd(string command)
{
StringBuilder sb = new StringBuilder();
string version = System.Environment.OSVersion.VersionString;//讀取作業系統版本
if (version.Contains("Windows"))
{
using (Process p = new Process())
{
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;//是否指定作業系統外殼程序啟動程式
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;//不顯示dos指令行視窗
p.Start();//啟動cmd.exe
p.StandardInput.WriteLine(command);//輸入指令
p.StandardInput.WriteLine("exit");//退出cmd.exe
p.WaitForExit();//等待執行完了,退出cmd.exe
using (StreamReader reader = p.StandardOutput)//截取輸出流
{
string line = reader.ReadLine();//每次讀取一行
while (!reader.EndOfStream)
{
sb.Append(line).Append("<br />");//在Web中使用<br />換行
line = reader.ReadLine();
}
p.WaitForExit();//等待程式執行完退出程序
p.Close();//關閉程序
reader.Close();//關閉流
}
}
}
return sb.ToString();
}
使用舉例:
Label1.Text = ExecuteCmd("ipconfig /all");
Label2.Text = ExecuteCmd("ping www.baidu.com");