Saturday, September 19, 2009

Download data using FTP or HTTP with C#

If you want to download data via FTP or HTTP then you can use this solution. you can Use the System.Net.WebClient to achieve this. The URI determines whether a file (file://) , FTP (FTP://) or HTTP (HTTP:// or HTTPS://) scheme is to be used.

On .Net2.0 there is an Async Version get added which will allows you download data asynchronously as a background task using its own thread from the thread pool. WebClient object can handle one async download at a time. its not useful for downloading many files concurrently , but if you want to do this then you can use multiple WebClient objects. if you want to Cancel the current download using CancelAsync.

There are Several Methods:

1. OpenRead - returns a System.IO.Stream
OpenReadAsync - async downloading use the handler OpenReadCompleted

2. DownloadData - returns a ByteArray
DownloadDataAsync - use handler DownloadDataCompleted

3. DownloadFile - Saves to a local file
DownloadFileAsync - use handler DownloadFileCompleted

4. DownloadString - returns a String ( introduced in .net 2.0)
DownloadStringAsync - use handler DownloadStringCompleted

Here is Sample code:

using System.IO;
using System.Net;
using System.Text.RegularExpressions;

string remoteUri = "";
WebClient client = new WebClient();
string str = client.DownloadString(remoteUri);

** if you are using proxy then you need extra code to code around it.
on my next post i will tell you how you can download data using Proxy.
Downloading data over FTP, Downloading data over HTTP, FTP, HTTP, Net.WebClient

No comments:

Post a Comment