post 和使用 Flurl 将流响应保存到文件的正确方法是什么
What is the correct way to post and save stream response to file using Flurl
我正在尝试实现异步 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);
}
我正在尝试实现异步 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);
}