概述C#執(zhí)行ping命令
C#執(zhí)行ping命令
首先,我們用使用Process類,來(lái)創(chuàng)建獨(dú)立的進(jìn)程,導(dǎo)入System.Diagnostics,using System.Diagnostics;
實(shí)例一個(gè)Process類,啟動(dòng)一個(gè)獨(dú)立進(jìn)程Process p = new Process();
Process類有一個(gè)StartInfo屬性,這個(gè)是ProcessStartInfo類,包括了一些屬性和方法。
下面我們用到了他的幾個(gè)屬性:
◆設(shè)定程序名p.StartInfo.FileName = "cmd.exe";
◆關(guān)閉Shell的使用p.StartInfo.UseShellExecute = false;
◆重定向標(biāo)準(zhǔn)輸入p.StartInfo.RedirectStandardInput = true;
◆重定向標(biāo)準(zhǔn)輸出p.StartInfo.RedirectStandardOutput = true;
◆重定向錯(cuò)誤輸出p.StartInfo.RedirectStandardError = true;
◆設(shè)置不顯示窗口p.StartInfo.CreateNoWindow = true;
上面幾個(gè)屬性的設(shè)置是比較關(guān)鍵的一步。
既然都設(shè)置好了那就啟動(dòng)進(jìn)程吧,p.Start();
C#執(zhí)行ping命令,輸入要執(zhí)行ping命令,這里就是ping了,
p.StandardInput.WriteLine("ping -n 1 www.iwebtrados.com.cn");
p.StandardInput.WriteLine("exit");
從輸出流獲取命令執(zhí)行結(jié)果,string strRst = p.StandardOutput.ReadToEnd();
利用C#執(zhí)行ping命令
這里我寫的是一個(gè)窗體程序。首先添加textbox,listbox,button控件,其中textbox錄入域名或IP,listbox顯示結(jié)果.
在button1_click事件鍵入
- privatevoidbutton1_Click(objectsender,EventArgse)
- {
- Pingp1=newPing();//只是演示,沒(méi)有做錯(cuò)誤處理
- PingReplyreply=p1.Send(this.textBox1.Text);//阻塞方式
- displayReply(reply);//顯示結(jié)果
- }
- privatevoiddisplayReply(PingReplyreply)//顯示結(jié)果
- {
- StringBuildersbuilder;
- if(reply.Status==IPStatus.Success)
- {
- sbuilder=newStringBuilder();
- sbuilder.Append(string.Format("Address:{0}",reply.Address.ToString()));
- sbuilder.Append(string.Format("RoundTriptime:{0}",reply.RoundtripTime));
- sbuilder.Append(string.Format("Timetolive:{0}",reply.Options.Ttl));
- sbuilder.Append(string.Format("Don'tfragment:{0}",reply.Options.DontFragment));
- sbuilder.Append(string.Format("Buffersize:{0}",reply.Buffer.Length));
- listBox1.Items.Add(sbuilder.ToString());
- }
- }
也可以做異步的處理,修改button1_click,并添加PingCompletedCallBack方法
- privatevoidbutton1_Click(objectsender,EventArgse)
- {
- Pingp1=newPing();
- p1.PingCompleted+=newPingCompletedEventHandler(this.PingCompletedCallBack);
- //設(shè)置PingCompleted事件處理程序
- p1.SendAsync(this.textBox1.Text,null);
- }
- privatevoidPingCompletedCallBack(objectsender,PingCompletedEventArgse)
- {
- if(e.Cancelled)
- {
- listBox1.Items.Add("PingCanncel");
- return;
- }
- if(e.Error!=null)
- {
- listBox1.Items.Add(e.Error.Message);
- return;
- }
- StringBuildersbuilder;
- PingReplyreply=e.Reply;
- if(reply.Status==IPStatus.Success)
- {
- sbuilder=newStringBuilder();
- sbuilder.Append(string.Format("Address:{0}",reply.Address.ToString()));
- sbuilder.Append(string.Format("RoundTriptime:{0}",reply.RoundtripTime));
- sbuilder.Append(string.Format("Timetolive:{0}",reply.Options.Ttl));
- sbuilder.Append(string.Format("Don'tfragment:{0}",reply.Options.DontFragment));
- sbuilder.Append(string.Format("Buffersize:{0}",reply.Buffer.Length));
- listBox1.Items.Add(sbuilder.ToString());
- }
- }
【編輯推薦】