我正在尝试实现一个异步POST文件,并使用Flurl直接读取对文件的响应。下面的代码可以正常工作,但不能确定使用c.Result.CopyTo
或c.Result.CopyToAsync
?将文件写入流。哪种方法正确?
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);
您当然可以CopyToAsync
在这里使用,但是如果您避免使用ContinueWith
,它会更干净,因为引入async
/以来,它通常没有那么有用await
。它还使配置HTTP流更干净。我会选择这样的东西:
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句