Click here to Skip to main content
15,886,812 members
Articles / Web Development / ASP.NET
Tip/Trick

Setting timeout property for System.Net.WebClient Class

Rate me:
Please Sign up or sign in to vote.
4.33/5 (3 votes)
30 Mar 2010CPOL 72.9K   2  
Introduction...
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.


Using the code 

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. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Symphony
India India
This member doesn't quite have enough reputation to be able to display their biography and homepage.

Comments and Discussions

 
-- There are no messages in this forum --