Setting timeout property for System.Net.WebClient Class






4.33/5 (3 votes)
Introduction...
As the title of the article describes this article is going to describe a very simple but very helpful topic. Every now and then we are faced with a situation where we have to provide functionality to download/upload the files.The WebClient class Provides common methods for sending data to and receiving data from a resource identified by a URI, But the problem is when we try to download a bigger file which takes more time to download we get a Timeout Exception
and Web Client class does not provide any property where we can specify/set the timeout value.
You can make use of the WebRequest class to set the timeout property.The code contains a Wrapper class called ExtendedWebClient which is inherited from the WebClient class and a overrided method of type WebRequest which sets the timeout property.The ExtendedWebClient class can be used as WebClient Class but with the timeout property being set.
public class ExtendedWebClient: WebClient { private int timeout; public int Timeout { get { return timeout; } set { timeout = value; } } public ExtendedWebClient(Uri address) { this.timeout = 600000;//In Milli seconds var objWebClient = GetWebRequest(address); } protected override WebRequest GetWebRequest(Uri address) { var objWebRequest= base.GetWebRequest(address); objWebRequest.Timeout = this.timeout; return objWebRequest; } }Now you can just Instantiate the ExtendedWebClientclass nad use all the available methods and properties of WebClient class along with the timeout property being set to 600000 ms.