Reputation: 51
I am using a httpclient to save a file from an URI. The pdf is not saving a pdf file consistently. I solved the problem but I wanted to see if anyone can explain why this happened in the first place. The original code was:
using (var pdfStream = File.Create(savePdf))
result.Content.CopyToAsync(pdfStream);
The code that worked was:
File.WriteAllText(savePdf, result.Content.ReadAsStringAsync().Result);
Upvotes: 1
Views: 699
Reputation: 142014
CopyToAsync returns a Task before the task has completed. Your Using block will exit and pdfStream will be disposed before the CopyToAsync method has completed.
Either add await or .Wait().
Upvotes: 5