Code Sample: Programmatically Download File Using C#
While browsing forums today I came across a question which asked for a solution to download a file from a web server programmatically. The solution is very simple and below is the code which achieves the goal. Here I am downloading a file asynchronously on Button Click.
1: private void buttonDownloadFile_Click(object sender, EventArgs e)
2: {
3: string url
4: = @"http://www.thereforesystems.com/wp-content/uploads/2008/08/image35.png";
5:
6: // Create an instance of WebClient
7: WebClient client = new WebClient();
8:
9: // Hookup DownloadFileCompleted Event
10: client.DownloadFileCompleted +=
11: new AsyncCompletedEventHandler(client_DownloadFileCompleted);
12:
13: // Start the download and copy the file to c:\temp
14: client.DownloadFileAsync(new Uri(url), @"c:\temp\image35.png");
15: }
16:
17: void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
18: {
19: MessageBox.Show("File downloaded");
20: }
You can also download the file synchronously using WebClient.DownloadFile() method.
46 Responses to Code Sample: Programmatically Download File Using C#
Leave a Reply Cancel reply
Top Posts
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Windows 7 Control Panel In Classic Mode
- More Details Emerge On Microsoft Master Certification
- Use SqlConnection With LINQ To SQL
- Free Icons And Images With Visual Studio 2008
- Capture XML In WCF Service
- Dynamic Sort With LINQ
- StyleCop Tutorial
Tags
.Net 2010 ADO.NET ASP.NET Azure Blogging Books Browsers C# Certification Cloud Computing Code Snippets Community Data Services Eclipse Entity Framework Google IDE Java LINQ Mac Microsoft Museum NetBeans Office Oracle REST SharePoint Silverlight SQL Server T-SQL Tips Tools Training Visual Studio Visual Studio 2010 WCF Web Windows Windows 7 Windows Forms Windows Live WMI WPF XAML


Hello! Thank you for the post.
I am anxious to know if this will work on computer behind PROXY?
Thanks. If it does not work then you can set WebClient.UseDefaultCredentials. This should do the trick. And if you have to specify credentials for your proxy explicitly then you can set WebClient.Credentials property.
Hope this helps.
Thank dude for a quick reply!
I’ll try this.
Good Day!
Hello! Thank you for the post.
Bikash,
Thank you for your comment.
Hi,
I need to know if this Code works Successfully for Downloading a file with .pdf extension on my local system drive I’hv tried a similar but failed to do so
I need to download a file opened in a browser with .pdf extension
Plz Help
Help Would Be Appreciated
Himanshu
Hi Himanshu,
It should work fine with any file extension.
HI,
thx for the quick reply
i’ll just check and report back
thx again.
hi all.. very use full article but.. can we use it in web aplication.. on internet.. where ever i get example of WebClient , i get it in window application, in web application, is it possible to add event handler “DownloadDataCompletedEventHandler” to track download complete ? any help on this will be appreciated.. thank u..
aha … thanks for help
The code is really helpful, but i Need one clarification
I want to download a file from the web and the url is the indirect url (there is no filename in the url it has query param), so code does not know about the file name, how can i get the file name
I ran through few stuffs for indirect url using webclient downloadfile method.
I have get filename in content-dispostion or content-location of the response headers.
But some times the response header does not have content-type or content-disposition (to get file name) in it, in this situation what can i do here to get the real file name?
Any help will be appreciated from this end.
Thanx dude
Thanks for the code.
I am trying to write a program that will be scheduled to run everyday to download a file from an ftp site. The file is created automatically everyday and saved to the ftp site by another program. The file is named abc_datetimestamp.txt. Since the file name contains the create timestamp, the file name changes everyday. Therefore I do not know what the exact file name will be. Is there any way I can use the WebClient.DownloadFile method without knowing the complete file name? Or is there a way I could retrieve the file name from the ftp site and then feed it to the webclient method? Please note that the file is deleted after it is downloaded from the ftp site, so at any one time, there will be only one file that starts with abc.
Any help will be appreciated.
Rajib,
Your best bet will be to transfer the file via ftp. You can download all files in a folder this way. There are many ftp libraries available for .NET both commercial and open source.
If network goes down while downloading file, then downloading will break. If I am downloading a big file, then is there any way so that file downloading can continue from same point???
Raja,
If downloading the file programmatically is not a strict requirement then you can use a tool such as http://www.freedownloadmanager.org/
The tool is superb and incorporates features such as resume support, scheduler and much more.
Hi Deepak,
Thanks for your reply, but only those tools can help me that has support for command-line. Because, initiating downloading and uploading from program is the requirement. I want to initiate uploading or downloading from C# program. I have zipped and split the files through program. Pls suggest what to do.
Raja,
Have a look at this http://en.wikipedia.org/wiki/Comparison_of_download_managers
You can find a download manager with works with command line interface. According to the page Free Download Manager also has a command line interface but I have never tried it.
Hi Deepack ,
I would like to thank for the post . i was trying to run the sample code but unfortunately . it couldn’t download the file. it created the file but it had nothing . I’m looking forward for your help.
Best Regards, Miretab
Did you get any errors?
What happens when you download the same file in a browser?
Deepak,
Thanks for the article. I think it will help with the problem I’m having. The file is created, but empty. When I download the file from the website it comes up with a dialogue where I can save from. Any idea what I can do?
Few things to look for:
1. Are you behind a proxy? If yes then make sure that your application works with valid proxy credentials.
2. Do you get any errors? If yes, then can you post them here?
Hi Deepak,
Is there any way to determine whether a folder is locked by windows using C# code?
I want to start working on a folder when windows complete the copy process on it.
I didn’t start that copy process so I dont hav any handle to this process.
Hi Deepak,
Can I get handle of the process that is operating on a folder. I have path and name of the folder.
Pls. reply if you have some idea.
Thanks
Raja
Hi!!!
While uploading a file how to restrict its type in C#.
Regards,
Kavita.
Mind Blowing Post
Thanks Adit :)
Hello, does the code need any assembly reference and using system;?
i am using expression blend 4 with VS2010 .netframework 3.5
Hi,
need to download mp3 file from URL, but need to open save dialog. Is it possible?
Its very urgent
Thanks,
Using this code i am not able to download email attachment from exchange server, please let me know how do i get the url of an attachment.
Hi, i want to ask about your method.
I’m trying to download video from youtube, but i see it ‘s very far from my experient.So,please show me how to do that? If i use your methods, i can’t do that, because on youtube, videos are not exist with extension….Thanks
Hi, Assume one client is uploading a file to a ftp server and i want to watch that file uploading and to download that file soon after it was completely uploaded. please give me a solution.
Thanks in advance
Sakthivel.s
Thanks for the code solution! I converted it to vb.net for 2010 and it works. Enjoy!
Imports System.Web
Imports System.IO
Imports System.Text
Imports WebFileDownload
Imports System.Net
Imports System.ComponentModel
Public Class Form1
Private Sub buttonDownloadFile_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonDownloadFile.Click
Dim url As String = “http://www.thereforesystems.com/wp-content/uploads/2008/08/image35.png”
‘ Create an instance of WebClient
Dim client As New WebClient()
‘ Hookup DownloadFileCompleted Event
AddHandler client.DownloadFileCompleted, New AsyncCompletedEventHandler(AddressOf client_DownloadFileCompleted)
‘ Start the download and copy the file to c:\temp
client.DownloadFileAsync(New Uri(url), “c:\temp2\image35.png”)
End Sub
Private Sub client_DownloadFileCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
MessageBox.Show(“File downloaded”)
End Sub
End Class
Thanks Richard. Your code will help readers who are looking for a VB.NET sample.
Hi Richard
I have used simillar code for c# as below:
1. WebClient fileReader = new WebClient();
2. fileReader.Credentials = CredentialCache.DefaultCredentials;
3. fileReader.DownloadFile(“http://msdn.microsoft.com/hi-in/magazine/rss/default(en-us).aspx?z=z&iss=1″, “D:\\date.txt”);
The problem I am facing is that when I give url of local site (that is on our intranet) then above code successfully download the file. But when url is of external website then it give error like “The remote name could not be resolved: ‘msdn.microsoft.com’ ”
Any suggestion to get rid of such error.
I am working on a program Personal online memory i need to upload and download images , videos , Documents , Songs i can upload but am not able to download it ?? Please help
The WebClient class implements IDisposable, and thus should be wrapped with a using statement or at least be dispose.
Shimmy,
Thanks for the tip. Using it shall be :)
Hi Deepak,
On a certain website a table is showed.
I want to download that data. However the only(?!) way to do it is to get/download the XML-file behind the table.
How can i do that?
Best regards,
Louk
For the XML you can refer this site for help: http://deepumi.wordpress.com/2010/03/14/yahoo-geocoding-api-service-in-asp-net-3-5-c-using-webclient-asynchronously/
which library should i use if it is coded in the MS visual C++.
thanks
Susan
hi. i used this code to download a file but i get an html instead of a csv. when i paste the uri directly on the browser, it initiates download, but not when i do it through an app. help please.
Does it work in windows application..??
Hi
can we read some content out of that HTML downloaded file?
i want “Maincontent” data from the HTML file, which have been downloaded from URL
it is not working in windows 7
Thank you!