【发布时间】: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问题(记事本将显示CR和LF的换行符)。您确定没有对服务器上的文件进行任何更改吗?您在左侧的文件是从服务器下载的(手动)还是上传前的原始文件? -
取决于原始编码。试试
webClient.Encoding = Encoding.UTF8;ASCII 编码是不可能的。 -
我手动检查下载文件,文件正常。我将尝试在不使用 using() 的情况下下载文件并写入
标签: c# webclient downloadfileasync