读书人

PING下令小工具出错小白求教

发布时间: 2013-07-01 12:33:04 作者: rapoo

PING命令小工具出错小白求教
本帖最后由 xsnetangel 于 2013-06-17 12:26:34 编辑 在输入正确的IP时就没有问题,输入错误的IP格式就出现:Ping 请求期间发生异常。期望前辈们给予提点:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Ping ping = new Ping();
PingReply result = ping.Send(IP.Text);
if (result.Status == IPStatus.Success)
MessageBox.Show("连接成功");
else
MessageBox.Show("连接失败");
IPAddress ip;

try
{
ip = IPAddress.Parse(IP.Text);
}
catch (Exception error)
{
MessageBox.Show("IP地址输入格式错误 " + error.Message);

}
}
[解决办法]

Ping ping = new Ping();            
IPAddress ip;
if(!System.Net.IPAddress.TryParse(IP.Text, out ip))
{
MessageBox.Show("IP地址输入格式错误 " + error.Message);


return;
}
try
{
PingReply result = ping.Send(ip);
if (result.Status == IPStatus.Success) MessageBox.Show("连接成功");
}
catch (Exception error)
{
MessageBox.Show("连接失败:" + error.Message);
}

读书人网 >C#

热点推荐