Uploading & Downloading a file using C#

In this post we will know how to download a file from a web site and upload a file to a web site through c# application. The System.Net namespace contain most of the .NET base class that deal with networking from perspective of the client.
The System.Net namespace is generally concerned with Higher-level operations.
for example download and upload files and making requests using the HTTP and other protocols.

Download Files from Web using C#

This example shows how to download files from any website to local disk. The simply way how to download file is to use WebClient class and its method DownloadFile. This method has two parameters, first is the url of the file you want to download and the second parameter is path to local disk to which you want to save the file.

The following code shows how to download file synchronously. This method blocks the main thread until the file is downloaded or an error occur (in this case the WebException is thrown).

using System.Net;

WebClient webClient = new WebClient();

webClient.DownloadFile(“http://www.ujjwaladatta.com/myfile.txt”, @”c:\websiteFiles\myfile.txt”);

UploadFiles to Web Using C#

The webClient class also features UploadFile() and UploadData() methods. The diffrence between them is that UploadFile() uploads a specified file given the file name, While UploadData() uploads binary data, which is supplied as an array of bytes:

WebClient Client = new WebClient();

Client.UploadFile(“http://www.ujjwaladatta.com/Members/index.aspx”, “c:\wesiteFiles\newfile.aspx”);

byte [] image; //code to initialise image so it contains all the binary data for some jpg file

client.UploadData(“http://www.ujjwaladatta.com/Members/images/logo.jpg”, image);

Advertisements

One thought on “Uploading & Downloading a file using C#

  1. HAI THIS IS RAHEEM VALI FROM HYDERABAD.
    THANKS ALOT ,IAM ALSO SECRCHING FOR THIS TYPE OF CODE.

    MY DOUT IS THIS IS APLICABLE ON GMAIL
    PLS REPLY ….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s