jdMiami
jdMiami

Reputation: 51

.NET httpclient not saving a pdf file consistently

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

Answers (1)

Darrel Miller
Darrel Miller

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

Related Questions