使用webClient.DownloadFileAsync下载并保存文件,而无需单击按钮



我正在编写一个C#Win窗体应用程序,我希望在没有用户干预的情况下以编程方式下载并将文件保存到客户端计算机。

我发现了几个建议,比如这个关于stackoverflow的建议:如何在C#中从网站下载文件

我尝试使用webClient.DownloadFileAsync方法以及csharp示例中的一个建议http://www.csharp-examples.net/download-files/异步下载文件

如果我直接将URL插入Firefox或IE,所需的文件会出现在一个对话框中,我需要单击"打开"或"保存"。我希望能够下拉文件并保存它,而无需用户单击任何按钮。

在WinForm中测试时,我确实有一个按钮点击事件。我遇到的问题是,如果我使用webClient.DownloadFileAsync示例,则不会下载任何文件。我还在表单中添加了DownloadFileCompleted和DownloadProgressChanged事件处理程序以及progressBar1

我在webClient_DownloadFileCompleted中添加了一个MessageBox,消息立即显示,但没有下载任何文件。我在下面列出了我迄今为止尝试过的两个示例。我有System.Net、System.IO和System.Diagnostics的using语句;

使用webClient.DownloadFileAsync,是否有一种方法可以在不需要用户单击按钮的情况下下载和保存文件?谢谢

我尝试过的第一个例子:

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");
}

我尝试过的第二个例子:

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);
        }
    }
}

我甚至尝试在点击事件中调用后一种方法,并传递URL和保存位置的参数,但仍然没有下载任何文件。

我喜欢第二个例子,因为我可以为不同的文件传递不同的URL和保存位置。

有人能建议我如何使用webClient代码下载和保存文件,但不需要用户与对话框交互吗?一旦文件下载,我就在幕后使用它来完成任务。谢谢

尝试使用Fiddler捕获下载请求:http://www.telerik.com/fiddler

查看手动下载文件和在应用程序中下载文件时的请求/响应是否不同。

最新更新