0

我遇到了 WebClient.DownloadFile() 的问题,它在慢速连接上始终错误地下载文件。下载不正确,我的意思是文件的大小(以字节为单位)与预期的大小不匹配。它可以在正常的以太网连接上正常下载。这是代码:

internal void Start(List<FileInformation> fileList)
{
    filesCompleted = 0;
    totalNumberFiles = fileList.Count;

    using (webClient = new WebClient())
    {
        foreach (var file in fileList.OrderBy(x => x.Name))
        {
            if (file.Size > 0)
            {
                DownloadFile(file);
            }
            else
            {
                File.Create(AppStrings.FilebinPath + file.Name);
            }

            filesCompleted++;
            UpdateProgress(Convert.ToDouble(((filesCompleted / (double)totalNumberFiles) * 100).ToString("N2")));
        }
    }
}

private void DownloadFile(FileInformation file)
{
    var filePath = AppStrings.FilebinPath + file.Name;
    webClient.DownloadFile(new Uri(AppStrings.FilebinServer + file.Name), filePath);

    //Recursively retry the download until it downloads correctly.
    if ((new FileInfo(filePath).Length != file.Size))
    {
        //Added this debugging info to figure out what is going wrong.
        AppLog.WriteError("Failed to download file: " + filePath + "\nSize downloaded: " + new FileInfo(filePath).Length + "\nCorrect size: " + file.Size);
        DownloadFile(file);
    }
}

对于慢速网络连接,有没有更可靠的方法来做到这一点?

编辑:这不是重复的,因为问题是关于同步下载文件,它询问最可靠的方法是什么。另一个主题是询问为什么 DownloadFilesAsync 无法正确下载文件。

编辑2:尝试了以下代码并得到了与我的第一条评论@David 中描述的相同的行为:

byte[] data = null;
var webRequest = (HttpWebRequest)WebRequest.Create(new Uri(AppStrings.FilebinServer + file.Name));
webRequest.ProtocolVersion = Version.Parse("1.0");
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
    using (var streamReader = webResponse.GetResponseStream())
    {
        data = new byte[(int)webResponse.ContentLength];

        for (var i = 0; i < data.Length; i++)
        {
            data[i] = Convert.ToByte(streamReader.ReadByte());
        }
    }
}
4

0 回答 0