您的位置:首页 > 理论基础 > 计算机网络

c#检测网络连接问题我没有看到好的方法(转)

2011-03-31 10:52 323 查看
c#检测网络连接问题我没有看到好的方法,都是通过与外网(或者局域网服务器)传递信息检测的。

我看些下下来了

代码:

private void button1_Click(object sender, EventArgs e)
{
string ip;
ip = "10.1.148.1";
// string ip = "192.192.132.229";

// string strRst = CmdPing(ip);

// MessageBox.Show(strRst);
string str = CmdPingh(ip);
MessageBox.Show(str);

}
private static string CmdPing(string strIp)//方法1

{

Process p = new Process();

p.StartInfo.FileName = "cmd.exe";

p.StartInfo.UseShellExecute = false;

p.StartInfo.RedirectStandardInput = true;

p.StartInfo.RedirectStandardOutput = true;

p.StartInfo.RedirectStandardError = true;

p.StartInfo.CreateNoWindow = true;

string pingrst;

p.Start();

p.StandardInput.writeLine("ping -n 1 "+strIp);

p.StandardInput.writeLine("exit");

string strRst = p.StandardOutput.ReadToEnd();

if(strRst.IndexOf("(0% loss)")!=-1)

pingrst = "连接";

else if( strRst.IndexOf("Destination host unreachable.")!=-1)

pingrst = "无法到达目的主机";

else if(strRst.IndexOf("Request timed out.")!=-1)

pingrst = "超时";

else if(strRst.IndexOf("Unknown host")!=-1)

pingrst = "无法解析主机";

else

pingrst = strRst;

p.Close();

return pingrst;

}
public static string CmdPingh(string _strHost) //与上面的方法一样,不同写法而已
{
string m_strHost = _strHost;

Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
string pingrst = string.Empty;
process.StartInfo.Arguments = "ping " + m_strHost + " -n 1";
process.Start();
process.StandardInput.AutoFlush = true;
string temp = "ping " + m_strHost + " -n 1" ;
process.StandardInput.writeLine(temp);
process.StandardInput.writeLine("exit");
string strRst = process.StandardOutput.ReadToEnd();
if(strRst.IndexOf("(0% loss)")!=-1)
pingrst = "连接";
else if( strRst.IndexOf("Destination host unreachable.")!=-1)
pingrst = "无法到达目的主机";
else if(strRst.IndexOf("Request timed out.")!=-1)
pingrst = "超时";
else if(strRst.IndexOf("Unknown host")!=-1)
pingrst = "无法解析主机";
else
pingrst = strRst;
process.Close();
return pingrst ;
}

private void button2_Click(object sender, EventArgs e)
{
jcip();
}

private void jcip()//方法2
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();

// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;

// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send ("10.1.148.1", timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
MessageBox.Show("连接正常");
}
else
{
MessageBox.Show("网络没有连接");
}

}

}


C#中运行命令行截取输出流的例子(C#中截取dos内容)

http://blog.csdn.net/jat_chipmore/archive/2008/09/20/2956166.aspx

说明:经常有朋友问如何在C#中运行一个dos命令,并截取输出、输出流的问题,这个问题我以前在Java中实现过,由于在C#中没有遇到过类似
的 情况,为了避免每次别人问都要一遍一遍演示的情况,特地做了一个简单的例子,实现在WinForm中ping一个网站,并且将ping的结果显示在一
个文本框中。



运行结果图

窗体设计器产生的代码:

namespace RunCMD
{
partial class CMDForm
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows 窗体设计器生成的代码

/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.txtCommand = new System.Windows.Forms.TextBox();
this.btnExecute = new System.Windows.Forms.Button();
this.tbResult = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 11);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(29, 12);
this.label1.TabIndex = 0;
this.label1.Text = "ping";
//
// txtCommand
//
this.txtCommand.Location = new System.Drawing.Point(41, 8);
this.txtCommand.Name = "txtCommand";
this.txtCommand.Size = new System.Drawing.Size(269, 21);
this.txtCommand.TabIndex = 1;
//
// btnExecute
//
this.btnExecute.Location = new System.Drawing.Point(316, 6);
this.btnExecute.Name = "btnExecute";
this.btnExecute.Size = new System.Drawing.Size(75, 23);
this.btnExecute.TabIndex = 2;
this.btnExecute.Text = "执行";
this.btnExecute.UseVisualStyleBackColor = true;
this.btnExecute.Click += new System.EventHandler(this.btnExecute_Click);
//
// tbResult
//
this.tbResult.Location = new System.Drawing.Point(8, 47);
this.tbResult.Multiline = true;
this.tbResult.Name = "tbResult";
this.tbResult.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.tbResult.Size = new System.Drawing.Size(383, 292);
this.tbResult.TabIndex = 3;
//
// CMDForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(403, 364);
this.Controls.Add(this.tbResult);
this.Controls.Add(this.btnExecute);
this.Controls.Add(this.txtCommand);
this.Controls.Add(this.label1);
this.Name = "CMDForm";
this.Text = "运行Command的例子";
this.ResumeLayout(false);
this.PerformLayout();

}

#endregion

private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtCommand;
private System.Windows.Forms.Button btnExecute;
private System.Windows.Forms.TextBox tbResult;
}
}

关键部分代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace RunCMD
{
/**
* 作者:周公
* blog:http://blog.csdn.net/zhoufoxcn
* 日期:2007-07-07
*
* */
public partial class CMDForm : Form
{
public CMDForm()
{
InitializeComponent();
}

private void btnExecute_Click(object sender, EventArgs e)
{
tbResult.Text = "";
ProcessStartInfo start = new ProcessStartInfo("Ping.exe");//设置运行的命令行文件问ping.exe文件,这个文件系统会自己找到
//如果是其它exe文件,则有可能需要指定详细路径,如运行winRar.exe
start.Arguments = txtCommand.Text;//设置命令参数
start.CreateNoWindow = true;//不显示dos命令行窗口
start.RedirectStandardOutput = true;//
start.RedirectStandardInput = true;//
start.UseShellExecute = false;//是否指定操作系统外壳进程启动程序
Process p=Process.Start(start);
StreamReader reader = p.StandardOutput;//截取输出流
string line = reader.ReadLine();//每次读取一行
while (!reader.EndOfStream)
{
tbResult.AppendText(line+" ");
line = reader.ReadLine();
}
p.WaitForExit();//等待程序执行完退出进程
p.Close();//关闭进程
reader.Close();//关闭流
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: