5

I have a web service, like this example for downloading a zip file from the server. When i open the URL through web browsers,I can download the zip file correctly. The problem is when I try to download the zip file through my desktop application. I use the following code to download:

WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(@"http://localhost:9000/api/file/GetFile?filename=myPackage.zip"), @"myPackage.zip");

After testing this, I get the myPackage.zip downloaded, but it is empty, 0kb. Any help about this or any other server code + client code example?

9
  • 3
    just a sanity check here: are you awaiting for your async request to finish? Commented Jul 31, 2018 at 14:24
  • is ProgressChanged ever called? verify in a debugger. if the thread (or the host process) terminates before the first chunk is transmitted, download will be aborted which would explain the zero size file. Commented Jul 31, 2018 at 14:25
  • 1
    @AlexanderToptygin Does he need to, though, if he's responding to events? Commented Jul 31, 2018 at 14:27
  • May you use the DownloadFile instead of DownloadFileAsync, Just to be sure. And tell us if it fix the issue ? Commented Jul 31, 2018 at 14:28
  • I am not using await, it says "Cannot await void". The progress changed isn't called ever, but the Complete yes. Commented Jul 31, 2018 at 14:29

1 Answer 1

11

You can try to use HttpClient instead. Usually, it is more convenient.

        var client = new HttpClient();
        var response = await client.GetAsync(@"http://localhost:9000/api/file/GetFile?filename=myPackage.zip");

        using (var stream = await response.Content.ReadAsStreamAsync())
        {
            var fileInfo = new FileInfo("myPackage.zip");
            using (var fileStream = fileInfo.OpenWrite())
            {
                await stream.CopyToAsync(fileStream);
            }
        }
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I needed. Thanks. (Just as an aside, "convenient" is relative. I could have done all this in one line of code in Perl, using LWP::UserAgent module, but then we have to work with what we have.) :-)
This is good, though it should be called out that client should be reused rather than making a new instance and disposing after each use. This article explains why

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.