C# Download file from webservice

丶灬走出姿态 提交于 2020-07-15 08:21:13

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/51615630/c-sharp-download-file-from-webservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!