使用HTTP处理文件下载期间丢失Internet连接

时间:2014-03-27 05:32:04

标签: c#

我使用以下代码从http服务器下载文件:

        int bytesSize = 0;
        // A buffer for storing and writing the data retrieved from the server
        byte[] downBuffer = new byte[4096];
        bool exceptionOccured = false;
        try
        {
            // Create a request to the file we are downloading
            webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Timeout = 60000;
            webRequest.ReadWriteTimeout = System.Threading.Timeout.Infinite;

            // Set default authentication for retrieving the file
            webRequest.UseDefaultCredentials = true;

            // Retrieve the response from the server
            webResponse = (HttpWebResponse)webRequest.GetResponse();

            // Ask the server for the file size and store it
            Int64 fileSize = webResponse.ContentLength;

            // Open the URL for download 
            strResponse = webResponse.GetResponseStream();

            // Create a new file stream where we will be saving the data (local drive)
            strLocal = File.Create(destFilePath);

            // Loop through the buffer until the buffer is empty
            while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
            {
                strLocal.Write(downBuffer, 0, bytesSize);
            };
        }
        catch (WebException we)
        {
            exceptionOccured = true;

            if (we.Status == WebExceptionStatus.NameResolutionFailure)
            {
                isExceptionOccured = true;
                string errMsg = "Download server threw a NOT FOUND exception for the url:" + "\n" + url + "\nVerify that the server is up and running.";
                MessageBox.Show(errMsg, "Cadence Download Manager", MessageBoxButton.OK, MessageBoxImage.Error);

            }
            else if (we.Status == WebExceptionStatus.Timeout)
            {
                isExceptionOccured = true;
                string errMsg = "Download server threw Timeout exception for the url:" + "\n" + url + "\nVerify that the server is up and running.";
                MessageBox.Show(errMsg, "Cadence Download Manager", MessageBoxButton.OK, MessageBoxImage.Error);

            }
            else if (we.Status == WebExceptionStatus.ProtocolError)
            {
                isExceptionOccured = true;
                string errMsg = "Download server threw Timeout exception for the url:" + "\n" + url + "\nVerify that the server is up and running.";
                MessageBox.Show(errMsg, "Cadence Download Manager", MessageBoxButton.OK, MessageBoxImage.Error);

            }
            else
            {
                isExceptionOccured = true;
                string errMsg = "Download server threw an unhandled exception for the url:" + "\n" + url;
                MessageBox.Show(errMsg, "Cadence Download Manager", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        catch (System.IO.IOException)
        {
            exceptionOccured = true;
            string errMsg = "Unable to read data from the download server for the url:" + "\n" + url + "\nVerify that the server is up and running.";
            isExceptionOccured = true;
        }
        catch (Exception)
        {
            exceptionOccured = true;
            string errMsg = "Unable to read data from the download server for the url:" + "\n" + url + "\nVerify that the server is up and running.";
            isExceptionOccured = true;
        }

问题是在下载过程中,当互联网连接断开时。控件卡在while循环中,并保持读写。它永远不会抛出任何异常或任何错误消息。我想处理下载过程中互联网连接中断的情况。这里缺少什么或错了什么?

2 个答案:

答案 0 :(得分:1)

根据我的说法,下面的步骤是可能的

1.您可以使用NetworkChange.NetworkAvailabilityChanged事件http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.networkavailabilitychanged.aspx,它会在局域网出现问题时告诉您,例如:网络电缆已拔下或用户自己禁用NetworkInterface。

2.如果因特网掉线你需要对自己的服务器有一些ping机制来检查服务器是否可以访问,你可以在开始下载ping时启动一个定时器并定期检查直到下载完成,一次下载完成或用户取消您可以停止计时器。

如下所示

        /// <summary>
        /// Event handler for network availability changed event.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="eventArgs">Event arguments.</param>
        private void NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs eventArgs)
        {
               ////Log or mail
        }

可以按以下方式订阅活动

NetworkChange.NetworkAvailabilityChanged += this.NetworkAvailabilityChanged;

答案 1 :(得分:1)

参考this

来自MSDN文档的

TCP alive