How to fix a WebClient timeout issue

The issue occurs when the time for generating the whole response of a WebClient request is longer than the default timeout (2 minutes / 60000 miliseconds) . So the solution is to increase this timout value. The WebClient class doesn't have such property or method, so you have 2 possibilities:

1. Use HttpWebRequest instead of WebClient and set its timeout by ReadWriteTimeout property. Of course the usage of this class is more complex than WebClisnt's one but it gives you more flexibility.

2. Make a derived class (wrapper) , which willset the timeout propery of the base class of the WebClient.


public class MyWebClient: WebClient
{
//time in milliseconds
private int timeout;
public int Timeout
{
get {
return timeout;
}
set {
timeout = value;
}
}

public
MyWebClient()
{
this.
timeout = 60000;
}


public MyWebClient(int timeout)
{
this.
timeout = timeout;
}

protected override WebRequest GetWebRequest(Uri address)
{
var result = base.GetWebRequest(address);
result
.Timeout = this.timeout;
return result;
}
}



The usage is pretty much the same as the WebClient's usage but we have to specify the new timeout in the constructor or by setting the Timeout property:

MyWebClient wClient = new MyWebClient(1800000);

UTF8Encoding objUTF8 = new UTF8Encoding();

try
{
byte[] data =
wClient.DownloadData(url);

File.WriteAllBytes(
System.AppDomain.CurrentDomain.BaseDirectory + @"\files\output.xls", data);

wClient = null;
objUTF8 = null;
}
catch (Exception ex)
{
objWebClient = null;
objUTF8 = null;

}

As you see this timeout property solves the problems by client side. The server response should also have longer timeout for generating the response. It is set by machine.config or web.config - httpRuntime section. Note that the timeout in web.config is specified in seconds.