请问如何用C#检测当前网络的状态,包括网速是否极慢等.

解决方案 »

  1.   

    p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.CreateNoWindow = true;
    p.Start();

    p.StandardInput.WriteLine("ping XXXXX");
    将返回值进行分析
      

  2.   

    检测是否已上网,及上网的方式(API)首先定义几个常量
    private const long INTERNET_CONNECTION_MODEM = 1;
    private const long INTERNET_CONNECTION_LAN = 2;
    private const long INTERNET_CONNECTION_PROXY = 4;
    private const long INTERNET_CONNECTION_MODEM_BUSY = 8;
    我还是用了默认的名字,程序中,多些共性,少些个性,我始终认为相当有必要。定义(引用)API函数
    [DllImport("wininet.dll")]
    public static extern bool InternetGetConnectedState (out long lpdwFlags , long dwReserved );private void button1_Click(object sender, System.EventArgs e)
    {
      long lfag;
      string strConnectionDev="";
      if(InternetGetConnectedState(out lfag,0))
        strConnectionDev="在线呀!!用的是 ";
      else
        strConnectionDev="不在线呀!!";
      if( (lfag & INTERNET_CONNECTION_MODEM ) > 0)
        strConnectionDev += "Modem";
      if( (lfag & INTERNET_CONNECTION_LAN ) > 0)
        strConnectionDev += "LAN";
      if( (lfag & INTERNET_CONNECTION_PROXY ) > 0)
        strConnectionDev += "a Proxy";
      if((lfag & INTERNET_CONNECTION_MODEM_BUSY) >0 )
        strConnectionDev += "Modem but modem is busy";
      MessageBox.Show(strConnectionDev);
    }
      

  3.   

    socket类的Connected属性往往不能精确的判断出网络是否连接,下面这段代码可以解决这个问题/// <summary>
    /// 是否已经连接
    /// </summary>
    public virtual bool Connected
    {
     get
     {
      try
      {
       //检查socket的状态是否可读
       if(m_socket.Connected && m_socket.Poll(0, SelectMode.SelectRead))
       {
        byte[] aByte = new byte[1];
        //因为TCP/IP协议无法精确的判断网络是否可用
        //试读一个字符,Peek参数指定读取的字符不会从缓冲区中移除
        //假如可读则表示连接可用
        if(m_socket.Receive(aByte, 0, 1, SocketFlags.Peek) != 0)
         return true;
        Close("Disconnected.");
        return false;
       }
      }
      catch(SocketException e)
      {
       OnException(e);
      }
      return m_socket.Connected;
     }
    }
      

  4.   

    InternetGetConnectedState可以判断连接状况,不过对于网速等可能不好判断