Download file with maximum timeout

  • Thread starter Thread starter Piotrekk
  • Start date Start date
P

Piotrekk

Hi

My question is:

What is the best way to download file giving it maximum timeout ( for
example 30 minutes ). After this time the operation should be
terminated ( maybe exception ? ). I was thinking about simplest
possible solution WebClient class but don't know if it is possible to
implement timeout...

Regards
Piotr Kolodziej
 
Piotrekk,

You can derive a class from the WebClient class and provide a public
method/property which will call the protected GetWebRequest method and then
set the Timeout property on that.

Or, you could just use the HttpWebRequest/HttpWebResponse (assuming you
are using HTTP, you can do it for any class that derives from WebRequest)
and set the Timeout property.
 
I did as you said:

public class MyWebClient : WebClient
{
public void MyDownload(Uri u)
{
Stream s = null;
FileStream fs = null;

try
{
WebRequest request = GetWebRequest(u);
WebResponse ws = request.GetResponse();

s = ws.GetResponseStream();
fs = new FileStream("ddd.avi", FileMode.Create);

byte[] buffer = new byte[32768];
int i;

while ((i = s.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, i);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (fs != null)
{
fs.Close();
}

if (s != null)
{
s.Close();
}
}
}
}

However i can see that it's not what I expected. I've observed that
Timeout affects only WebResponse ws =
request.GetResponse() line.
When i read from response Timeout doesn't change anything anymore.
It's not counting 0-timeout.
 
Back
Top