Reputation: 18117
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);
Upvotes: 4
Views: 1964
Reputation: 39319
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);
}
Upvotes: 2