Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Using WebClient to download a file

How to use the WebClient class to download a file from the Web and save it to a local path on your computer.

On Tuesday, June 22nd 2004 at 08:31 AM
By Andrew Pociu (View Profile)
*****   (Rated 4.5 with 31 votes)
Contextual Ads
More C# Resources
Advertisement

WebClient is a class that provides you with methods for sending and receiving data. That means you can download files from the web and save them using this class.


Here at Geekpedia we like to have a hands-on approach, so let's create a Windows Application project in Visual C# .NET.


Add to the form two textBoxes named downloadURL and savePath. Also add a button named btnDownload with the caption Download. If you want you can also add a label above each textBox containing the text 'URL to download from:' and 'Path to save to:', because that's what the textBoxes are about.



The form should look similar to this one:







As you can see, the text property of downloadURL in this example is set to the string 'http://www.geekpedia.com/pics/scrSaver/GeekpediaScr.zip' and the text property of savePath is set to 'C:\GeekpediaScr.zip'. It's also recommended that you set this the same, the file GeekpediaScr.zip on the Geekpedia.com server contains two screen savers very similar to the Windows XP one but with the Geekpedia logo (for more information view this).



WebClient is located in the System.Net namespace so you need to add at the beginning:






using System.Net;



The part where you code is surprisingly small. Just double click the Download button to invoke the btnDownload_Click() event.

Two lines of code are the only thing we need to use:






private void btnDownload_Click(object sender, System.EventArgs e)

{

WebClient wc = new WebClient();

wc.DownloadFile(downloadURL.Text, savePath.Text);

}

There's not much to say about this code because it's


self-explanatory. The first line of code inside the btnDownload_Click event creates a new instance of WebClient, named wc.

The second line uses method DownloadFile to download the file from the specified URL (downloadURL.Text) and save it to the specified path (savePath.Text).

More about DownloadFile can be found here (MSDN).



You can now test the project. Use the path to the Geekpedia ZIP file containing the screen savers if you wish (http://www.geekpedia.com/pics/scrSaver/GeekpediaScr.zip) and save it to a local path on your computer. When you press the download button the program looks like it crashed... actually it's downloading the file. After a few seconds the ZIP file GeekpediaScr.zip should be at the path specified by you.



There's way more to say about creating a file downloader. That's why recently I wrote a tutorial entitled Creating a download manager in C# that teaches you how to create a more advanced file downloader, that has a progress bar to show the user how much of the file was downloaded.

Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by moruso on Friday, May 20th 2005 at 12:17 PM

don't forget dispose the object, i have a problem because webclient object should be disposed if don't send an error where say that have problems with the webclient request, when i dispose the object this message dissapear

by kapil on Friday, January 6th 2006 at 02:25 AM

this article is very good. but can we download file on remote server.for egample instead of storing a file in c:\.. directory can i store the file in remote server's c directory or d directory?

by Andrei Pociu on Friday, January 6th 2006 at 02:42 AM

The first thing that comes to my mind is to use an FTP connection in your code to upload the file to a remote server as soon as it is downloaded.

by dinesh solanki on Sunday, February 26th 2006 at 08:16 AM

simple ............... but good approach
good..carry on.........

by Ramya on Thursday, August 3rd 2006 at 02:35 AM

hi
I used this code in my webapplication. In my local m/c it works fine but when i access my application using my system ip,
i get the exeception as \"An exception occurred during a WebClient request. \"

can u help on this?

by sanjay on Monday, December 3rd 2007 at 12:25 AM

sanju

by Gokul on Tuesday, April 1st 2008 at 03:29 PM

You guys are doing great work!! I writing an application which does the opposite of this. i need to upload files from local machine to remote server using webclient..i would like to know wat tasks has to be performed in the server to receive the file.

by Anil Goyal on Friday, May 16th 2008 at 03:08 AM


A very easy tutorial. along with that i got all other functions related to download/upload data/string .

Thanx.


by kokila on Monday, May 19th 2008 at 12:42 AM

hi,

downLoad files from server to local ,files are not downloaded separately in local machine

how to download files separately to local machine?


Regards
kokila

by kokila on Monday, May 19th 2008 at 12:42 AM

hi,

downLoad files from server to local ,files are not downloaded separately in local machine

how to download files separately to local machine?


by kokila on Monday, May 19th 2008 at 12:42 AM

hi,

downLoad files from server to local ,files are not downloaded separately in local machine

how to download files separately to local machine?


by Rui Oliveira on Wednesday, May 21st 2008 at 01:57 PM

I am trying to use WebClient to download a file from server to client with this code:

WebClient wc = new WebClient();
wc.DownloadFile(strFileFrom, strFileTo);

The strFileTo file is being created in server. Is not suppose to be created in client?
What could am I doing wrong?

Tks. Rui

by M on Wednesday, August 6th 2008 at 03:32 AM

the code is very simple but it take long runtime :(
how i solve that problem??
i put that code in the basic form in the form load
what can i do ???

by Prabhakaran on Wednesday, October 29th 2008 at 05:17 AM

Hi Guys!

i need some code for updating new version instead of old version windows application in .net C#

i developed windows application while run this exe i will get System tray icon. This application should check new version on url often if internet connection available on System. The Url path will have new Zipped File (filename_ddmmyy.zip) If the Zipped file date newer than old version it should download on temp folder and have to extract and find the exe to install automatically and if the old version running on system installation should kill the old version running and install new version.

i hope i will get code for the above requirement.

Thanks in Advance!

by jinh on Thursday, December 18th 2008 at 01:40 PM

when i click the download button, i got the following error. Please help me out!

System.Net.WebException: An exception occurred during a WebClient request. ---> System.UnauthorizedAccessException: Access to the path 'C:\Download' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
--- End of inner exception stack trace ---
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at System.Net.WebClient.DownloadFile(String address, String fileName)
at SPBackup.FormSPBackup.buttonRun_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnEnter(EventArgs e)
at System.Windows.Forms.Control.NotifyEnter()
at System.Windows.Forms.ContainerControl.UpdateFocusedControl()

Thank You in advance,
JH

by pranab on Thursday, January 22nd 2009 at 02:50 PM

I am facing an error message in the line of :
"this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize });".
The error message is: "Value of '283600' is not valid for 'Value'. 'Value' should be between 'minimum' and 'maximum'.
Parameter name: Value".
what can i do now? give me a Download Path's example for an website download.

by giacoder on Friday, January 23rd 2009 at 03:01 AM

Thank you for your simple sample :)

But I had an error until I added
wc.Proxy = null;
before
wc.DownloadFile(...);

by muayad on Sunday, February 15th 2009 at 04:14 AM

lol

by muayad on Sunday, February 15th 2009 at 04:14 AM

lol

by MakiS on Wednesday, March 25th 2009 at 05:26 AM

very simply.... u can add and procress method ?

by alaa telfah on Wednesday, July 8th 2009 at 02:18 AM

hi ,i need to download excel file from server
but the extention for this file is *.cfm .
so when i downloaded it as *.xls i can't change in it's data what can i do ???!!!
help me !!!!!

by anonomous on Wednesday, July 22nd 2009 at 12:26 AM

Simple and stupid. Rarely do you just open an anonomous ftp site. Least you could do is make this a useful example.

by may on Tuesday, August 11th 2009 at 03:30 AM

can v use this code for FTP download too

by kiran on Thursday, September 10th 2009 at 01:57 AM

how can i view(readonly) .pdf files or download it from server?
help me.thnx

by Иван on Sunday, October 18th 2009 at 11:45 PM

Эй! Я вас не понимаю!!

by Debasish on Sunday, December 13th 2009 at 04:45 AM

HI,While downloading files I need to show the progress bar and also the application will close to system tray.How can I do this?

by Ritesh on Thursday, December 24th 2009 at 12:35 AM

Very Nice.

by darshan on Sunday, June 13th 2010 at 12:42 PM

perfectly done with connecting n downloading file... wen i am processing the file i am getting this error
"The CLR has been unable to transition from COM context 0x596e80 to COM context 0x596ff0 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations."

plz help me soon

is there way to download only till a particular size specified by me...
plz be a bit soon got project work

by darshan on Sunday, June 13th 2010 at 12:43 PM

perfectly done with connecting n downloading file... wen i am processing the file i am getting this error
"The CLR has been unable to transition from COM context 0x596e80 to COM context 0x596ff0 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations."

plz help me soon

is there way to download only till a particular size specified by me...
plz be a bit soon got project work

by sanjay on Tuesday, November 16th 2010 at 01:33 AM

can u please tell me to auto download a file from server to client machine's desktop.

by Raza Usmani on Thursday, November 25th 2010 at 12:58 AM

but this code doesn't help with windows 7 and vista. Any solutions?

by amol on Thursday, February 24th 2011 at 04:15 AM

I am very trouble when i download file from local path from network path but this code is helped me and its very good and simple code i like it

by amol on Thursday, February 24th 2011 at 04:15 AM

I am very trouble when i download file from local path from network path but this code is helped me and its very good and simple code i like it

by amol on Thursday, February 24th 2011 at 04:16 AM

I am very trouble when i download file from local path from network path but this code is helped me and its very good and simple code i like it

by toanhoi on Wednesday, March 30th 2011 at 11:13 AM

Thanks you very much.I build sucessful .And I want to upload a file to Web Server ,but I don't write anything ? Can you help me,please?

by iScream on Saturday, April 30th 2011 at 05:13 AM

If you want to upload to a web server then google for C# ftp upload. D:

by hjkhjkhj on Monday, September 26th 2011 at 04:00 AM

jkjhk

by apply for a credit card with bad credit on Wednesday, December 14th 2011 at 10:02 AM

I am very trouble when i download file from local path from network path but this code is helped me and its very good and simple code i like it

by usb cable with ferrite on Tuesday, April 24th 2012 at 11:53 AM

I remember the old times when I used to work in an office and work with WebClient. I think things changed a lot lately. There are many other platforms, much easier to use and faster as well.

by Learn about MPH programs on Thursday, April 26th 2012 at 05:48 AM

Used to use this method of transfer almost daily, these days i prefer using team viewer or drob box to transfer my files to others. find them to be more user friendly and faster.

by Pradeep Kumar on Thursday, February 28th 2013 at 03:08 AM

Awesome...

This is working fine for me.
Thanks a lot


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources