连接断开时下载超时

时间:2012-03-08 17:10:03

标签: c# download timeout

  

可能重复:
  Timeout when connection is gone. HELP ME PLEASE

我想把我的代码暂停一下。 当文件被下载并且我没有上网时,它会计入60秒,如果连接没有回来,则会给出一条消息。

以下是代码:

    string novoNome;
    novoNome = strlocal + "\\" + zipNome;
    using (WebClient wcDownload = new WebClient())
    { 
          try
            {
                if (!Directory.Exists(strlocal))
                {
                    Directory.CreateDirectory(strlocal);
                }

                #region comunicação para download
                //string saida;
                // cria uma requisição do arquivo para download
                webRequest = (HttpWebRequest)WebRequest.Create(url);

                webResponse = (HttpWebResponse)webRequest.GetResponse();                    

                //Perguntar o tamanho do arquivo
                Int64 fileSize = webResponse.ContentLength;

                Uri uri = new Uri(url);

                // Abrindo arquivo para Download
                strResponse = wcDownload.OpenRead(uri);
                // Criando novo arquivo para salvar no HDD
                strLocal = new FileStream(novoNome, FileMode.Create, FileAccess.Write, FileShare.None);
                #endregion

                #region transferencia
                int bytesSize = 0;

                byte[] downBuffer = new byte[2048];                   

                try
                {
                    while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                    {                           
                        strLocal.Write(downBuffer, 0, bytesSize);
                        //if(this.IsAccessible)
                        this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize });
                        //wcDownload.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcDownload_DownloadProgressChanged);                              
                    }                        
                }
                catch (Exception e)
                {

                }
                #endregion                    
            }                
            finally
            {
                strResponse.Close();
                strLocal.Close();
            }
        }

有人能帮助我吗?

3 个答案:

答案 0 :(得分:0)

您可以在WebRequest实例上设置超时。类似于:webRequest.Timeout=60000; 如果超时,将抛出WebException。查看MSDN documentation了解详情。

答案 1 :(得分:0)

您应该将Timeout属性设置为WebRequest类。

http://msdn.microsoft.com/en-us/library/system.net.webrequest.timeout.aspx

答案 2 :(得分:0)

有两个超时,您可以设置一个是上述答案,即设置webRequest.Timeout。另一个对你的情况有用的是:

webResponse.GetResponseStream().ReadTimeout = 60000;    

当您的互联网连接已经消失60秒时会抛出异常....