I'm writing a C# Win-forms application that I want to programmatically download and save a file to a client computer without user intervention.
I've found several suggestions, such as this one on stackoverflow: How to download a file from a website in C#
I tried using the webClient.DownloadFileAsync method as well as a suggestion found at csharp-examples http://www.csharp-examples.net/download-files/ Download File Asynchronously
If I plug the URL into either Firefox or IE directly, the desired file appears in a dialog box where I would need to either click Open or Save. I want to be able to pull the file down and save it without the user having to click any buttons.
While testing this in a WinForm, I do have a button click event. The problem I'm encountering is that, if I use the webClient.DownloadFileAsync examples, no file is downloaded. I also added DownloadFileCompleted and DownloadProgressChanged event handlers and a progressBar1 to the form.
I added a MessageBox to the webClient_DownloadFileCompleted, and the message displays instantly but no file has been downloaded. I've included 2-samples of what I've tried so far below. I have the using statements for System.Net, System.IO and System.Diagnostics;
Using the webClient.DownloadFileAsync, is there a way to download and save the file without having the user click a button? Thanks.
The first example I've tried:
private void btnDownload_Click(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler
(webClient_DownloadProgressChanged);
webClient.DownloadFileAsync(new Uri("http://download.my.org/files/media/myFile.pdf"), @"C:
\mySaveLocation\");
}
The 2nd example I've tried:
public void DownloadFile(string urlAddress, string location)
{
using (webClient = new WebClient())
{
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
//The variable that will be holding the url address (making sure it starts with http://)
Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new
Uri(urlAddress) : new Uri("http://" + urlAddress);
try
{
//Start downloading the file
webClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I even tried calling this latter method in the click event and passing in the parameters for the URL and saving location, but still no file downloaded.
I like the 2nd example, because I can pass in a different URL and saving location for different files.
Would someone please suggest how I might use the webClient code to both download AND save the file, but without the user having to interact with a dialog? Once the file downloads, I'm working with it behind the scenes to accomplish things. Thanks.