0

I use WebClient to download files from a server, but the downloaded file is not same (the file size is wrong):

Here's a screenshot (the downloaded file is on the right):

Downloaded file

And here's my code:

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();
        }
    }

What's wrong?

  • I'm not sure whether this is causing the issue or not but I don't think that you should be using a `using` statement there. The point of a `using` block is disposing the object created when the block completes but you want to keep using that object until the file has been downloaded, so you should be disposing the `WebClient` inside `Client_DownloadFileCompleted` instead. – jmcilhinney Mar 02 '18 at 00:13
  • 1
    Also, are you sure that that encoding is correct? – jmcilhinney Mar 02 '18 at 00:13
  • This looks like an `EOL` problem (Notepad will display a line break for neither `CR` nor `LF`). Are you sure no changes are being made to the file on the server? Is your file on the left downloaded from the server (manually) **or is it the original file before uploading**? – 41686d6564 stands w. Palestine Mar 02 '18 at 00:33
  • It depends on the original encoding. Try `webClient.Encoding = Encoding.UTF8;` ASCII encoding is improbable. – Jimi Mar 02 '18 at 02:36
  • I check downloading file manually and file is OK. I will try download file without using() and write – Piotr Bibinin Mar 02 '18 at 10:57
  • I try other encoding options and still same result – Piotr Bibinin Mar 02 '18 at 10:57
  • I try other way I go to: http://piterrr70.nazwa.pl/www/app/content/Adam/Takie%20sobie.txt and Save as and downloaded file is incorect like using WebClient :/ wtf.. – Piotr Bibinin Mar 02 '18 at 11:23
  • @jmcilhinney I edit post. Look how I use WebClient, look ok ?! I don't have no idea why I get wrong file.. – Piotr Bibinin Mar 02 '18 at 13:04

1 Answers1

0

I probably find why this happened.. Server support only ASCII encoding look on file size after upload to server: enter image description here

I forced the coding and it worked :) Now files are same :)