使用.NET方法一次下载文件1的最可靠方法?

时间:2013-03-20 20:01:56

标签: c# .net download webclient

我遇到了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());
        }
    }
}

0 个答案:

没有答案