DownloadFile工作,DownloadFileAsync获取0字节文件

时间:2015-07-06 08:52:00

标签: c#

我试图从此网址下载git

https://github.com/msysgit/msysgit/releases/download/Git-1.9.5-preview20150319/Git-1.9.5-preview20150319.exe

我是使用DownloadFile做的,它工作正常。

现在我尝试使用Async方法,但它下载0字节文件。这是代码:

public void downloadFile(string urlAddress, string location)
{
    using (var downloadClient = new WebClient())
    {
        downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
        downloadClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

        Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("http://" + urlAddress);
        _downloadStopWatch.Start();
        try
        {
            downloadClient.DownloadFileAsync(URL, location);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        _downloadStopWatch.Stop();

        while (downloadClient.IsBusy) { }
    }
}

其中:

private string _location = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\test.exe";

并且urlAddress被输入到文本框中并传递给textbox.text

我检查已完成的处理程序,并说它已完成。

为什么我得到0字节文件?

1 个答案:

答案 0 :(得分:0)

已完成的方法参数AsyncCompletedEventArgs返回错误The remote name could not be resolved: 'https'

在这种情况下,你应该回到http

根据您的目标框架,您还可以使用await downloadClient.DownloadFileTaskAsync(urlAddress, location);