【发布时间】:2012-03-28 19:09:43
【问题描述】:
我想在我的代码中设置一个超时时间。当文件正在下载并且我没有互联网时,它会计数为 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);
webRequest.ReadWriteTimeout = 60000;
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 (WebException ex)
{
MessageBox.Show("WEB ERROO:" + ex.Message);
}
catch (Exception e)
{
MessageBox.Show("Erro:" + e.Message);
}
#endregion
}
catch (WebException ex)
{
MessageBox.Show("WEB ERROO:" + ex.Message);
}
catch (Exception e)
{
MessageBox.Show("Erro:" + e.Message);
}
finally
{
strResponse.Close();
strLocal.Close();
}
}
抱歉英语不好,我是巴西人。
请帮忙!!
谢谢。
【问题讨论】:
-
您是否考虑过异步读取,并在您的个人计时器读取 60 秒时切断该连接?
-
可能WebRequest.Timeout 是您要查找的属性或HttpWebRequest.ReadWriteTimeout。
-
无论是不是巴西人,请不要在您的帖子中写“HELP ME PLEASE”和“PLEASE HELP”。人们会提供帮助(这就是本网站的用途),只需清晰简洁地发布您的问题,并给他们一个机会。
-
作为一个小风格点,如果您的方法太大或太复杂以至于您试图将其与区域分离,您可能需要考虑重构一些块以分离功能......
-
Jason,我已经尝试使用计时器计数到 60,但没有用。另一个想法?谢谢
标签: c# visual-studio timer download timeout