问题
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