有一个程序需要长时间的连接网络,比如说下载工具。但是网络状况不好的话会断线,请问大家有谁知道怎么能够在检测到断线之后,自动重新连接网络。用C#怎么实现。最好能有一些程序示例。谢谢大家了。

解决方案 »

  1.   

    用try catch捕捉异常断线,在catch中重写连接程序
      

  2.   

    给你一个检测网络方法:
    可以创建一个Timer,定时检测,如果你的程序能Catch到断网后的异常,就写在Catch里面.        public static string CmdPing(string strIp)
            {
                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 = "Connect successfully.";
                else if (strRst.IndexOf("Destination host unreachable.") != -1)
                    pingrst = "Destination host unreachable.";
                else if ((strRst.IndexOf("Request timed out.") != -1) | (strRst.IndexOf("(100% loss)") != -1))
                    pingrst = "Request timed out.";
                else if (strRst.IndexOf("Unknown host") != -1)
                    pingrst = "Unknown host";
                else
                    pingrst = strRst;            p.Close();            return pingrst;
            }
      

  3.   

    论坛已经很多帖子说明了ping命令并不是判断网络中断的好方法(很多原因)。可以用API函数internetgetconnectedstate()具体使用参考MSDN。