【问题标题】:WebClient DownloadFileAsync() work IncorectWebClient DownloadFileAsync() 工作不正确
【发布时间】:2018-03-02 21:17:45
【问题描述】:

我用WebClient从服务器下载文件,但是下载的文件不一样(文件大小不对):

这是一个截图(下载的文件在右边):

这是我的代码:

public void StartDownload(string fileToDownloadLink, string PathToSaveFile)         ///////// Try check file type..
    {
        try
        {
            using (webClient = new WebClient())
            {
                //webClient.Encoding = Encoding.UTF8;
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);
                webClient.DownloadFileAsync(new Uri(fileToDownloadLink), PathToSaveFile);
            }
        }
        catch (WebException e)
        {
            MessageBox.Show(fileToDownloadLink);
            MessageBox.Show(e.ToString());
            Worker.CancelAsync();
            Application.Exit();
        }
    }

怎么了?

【问题讨论】:

  • 我不确定这是否会导致问题,但我认为您不应该在那里使用using 声明。 using 块的重点是处理块完成时创建的对象,但您希望在文件下载之前继续使用该对象,因此您应该在 Client_DownloadFileCompleted 内处理 WebClient
  • 另外,你确定那个编码是正确的吗?
  • 这看起来像一个EOL 问题(记事本将显示CRLF 的换行符)。您确定没有对服务器上的文件进行任何更改吗?您在左侧的文件是从服务器下载的(手动)还是上传前的原始文件
  • 取决于原始编码。试试webClient.Encoding = Encoding.UTF8;ASCII 编码是不可能的。
  • 我手动检查下载文件,文件正常。我将尝试在不使用 using() 的情况下下载文件并写入

标签: c# webclient downloadfileasync


【解决方案1】:

我可能会找到发生这种情况的原因.. 服务器仅支持 ASCII 编码在上传到服务器后查看文件大小: enter image description here

我强制编码,它工作了 :) 现在文件是一样的 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    相关资源
    最近更新 更多