Reputation: 139
For REST calls I use RestSharp, I have to call a service that has to return me a zip file which I will then save on File System
public bool DownloadZip(int id)
{
while (true)
{
var request = new RestRequest("download/zip", DataFormat.Json);
request.AddHeader("authorization", _token);
request.AddHeader("ID", _id.ToString());
request.AddQueryParameter("id", id.ToString());
var response = new RestClient(url).Get(request);
response.ContentType = "application/zip";
_logFile.Debug($"downloaded result {id}: {response.IsSuccessful} {response.StatusCode}");
if (response.IsSuccessful && !string.IsNullOrWhiteSpace(response.Content))
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(response.Content)))
{
using (var zip = File.OpenWrite(path: @"C:\temp\temp.zip"))
{
zip.CopyTo(stream);
}
}
return true;
}
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
_logFile.Warn($"Download Unauthorized {id}: {response.IsSuccessful} {response.StatusCode} {response.Content}");
_authToken = null;
}
else
{
_logFile.Error($"Download {id}: {response.IsSuccessful} {response.StatusCode} {response.Content}");
throw new Exception("DownloadZip Failed");
}
}
}
The line of code "zip.CopyTo(stream);
" returns "The stream does not support reading" as an error.
Is there any setting to set to ensure that it does not return an error?
Testing the call on Postman I noticed that in the response header I have Content-Disposition from this can I go back to the filename?
Upvotes: 0
Views: 2429
Reputation: 19640
With RestSharp 107 you can use
var stream = await client.DownloadStreamAsync(request);
It will give you a stream and you can do whatever you want with it.
Upvotes: 2