C# Download file from webservice

14,474

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);
            }
        }
Share:
14,474
Adnand
Author by

Adnand

I have nothing to tell.

Updated on June 15, 2022

Comments

  • Adnand
    Adnand almost 2 years

    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?