4

I am trying to implement an asynchronous POST file and read the response directly to a file using Flurl. The code below works fine but not sure about the writing stream to file using c.Result.CopyTo or c.Result.CopyToAsync? What method is correct?

var result = new Url(url)
                .WithHeader("Content-Type", "application/octet-stream")
                .PostAsync(new FileContent(Conversion.SourceFile.FileInfo.ToString()))
                .ReceiveStream().ContinueWith(c =>
                {
                    using (var fileStream = File.Open(DestinationLocation + @"\result." + model.DestinationFileFormat, FileMode.Create))
                    {
                        c.Result.CopyTo(fileStream);
                        //c.Result.CopyToAsync(fileStream);
                    }
                });

            if (!result.Wait(model.Timeout * 1000))
                throw new ApiException(ResponseMessageType.TimeOut);
Tomas
  • 17,551
  • 43
  • 152
  • 257

1 Answers1

2

You can certainly use CopyToAsync here, but that's cleaner if you avoid ContinueWith, which generally isn't nearly as useful since async/await were introduced. It also makes disposing the HTTP stream cleaner. I'd go with something like this:

var request = url.WithHeader("Content-Type", "application/octet-stream");
var content = new FileContent(Conversion.SourceFile.FileInfo.ToString());

using (var httpStream = await request.PostAsync(content).ReceiveStream())
using (var fileStream = new FileStream(path, FileMode.CreateNew))
{
    await httpStream.CopyToAsync(fileStream);
}
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
  • How to read StatusCode of the response in your example? I want to compare it to StatusCode == HttpStatusCode.OK and throw exception if not equal. – Tomas Nov 11 '19 at 13:05
  • Just do a try/catch on `FlurlHttpException`. https://flurl.dev/docs/error-handling/ – Todd Menier Nov 11 '19 at 17:09
  • See also answer to similar problem at https://stackoverflow.com/a/46859554/581414 – Ruskin May 05 '22 at 11:34