Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Download file from webservice

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?

like image 420
Adnand Avatar asked Dec 23 '22 05:12

Adnand


1 Answers

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);
            }
        }
like image 167
Denys Prodan Avatar answered Dec 25 '22 17:12

Denys Prodan