我有一个函数返回一个Stream,其中包含使用HttpContent下载文件的数据,HttpContent是HttpResponseMessage的内容(使用Owin)
对于那些感兴趣的人,我会在最后添加代码。
获取流的接口是:
async Task<Stream> DownloadLogFileAsync(...);
此函数的调用者想要创建一个包含此Stream数据的文件。根据{{3}},我应该使用StackOverFlow: How do I save a stream to File将Stream的内容保存在文件中。像这样:
(简化:不使用CancellationToken )
using(Stream downloadStream = await DownloadLogFileAsync(...) )
{
using (var fileStream = System.IO.File.Create(fullFileName))
{
await downloadStream.CopyToAsync(fileStream);
}
}
问题:
如果FileStream具有与downloadStream相同的缓冲区大小,它会提高性能吗?如何获取下载流的缓冲区大小?
问题结束
与问题无关,仅针对那些对OWIN / ASP文件下载感兴趣的人:
我有一个带有返回数据的函数的WCF服务。创建这些数据需要相当长的时间。返回数据的大小可能很大。因此决定将此功能分为两个功能:
当然,我的WCF服务需要适当的功能来取消创建,删除创建的文件并在文件变老且客户端忘记请求删除时进行一些清理。
所有功能都可以使用WCF完成。唯一需要OWIN / ASP的是对文件流的请求。
class OwinFileClient
{
private const string routePrefix = "SipLoggerFile/";
private readonly WebApiClient webApiClient = new WebApiClient() {...}
// Function to download the created file:
public async Task<Stream> DownloadSipLogFileAsync(Guid fileHandle)
{
var httpClient = this.webApiClient.CreateHttpClient();
string requestStreamFile = routePrefix + @"DownloadFile?fileHandle="
+ fileHandle.ToString("N");
var response = await httpClient.GetAsync(requestStreamFile)
.ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
string content = await response
.Content.ReadAsStringAsync()
.ConfigureAwait(false);
throw new System.Net.Http.HttpRequestException(
$"{response.StatusCode} [{(int)response.StatusCode}]: {content}");
}
// if here: success: deserialize the data
return await response.Content.ReadAsStreamAsync()
.ConfigureAwait(false);
}
}
WebApiClient:
class WebApiClient
{
public Uri baseAddress { get; set; }
public TimeSpan Timeout { get; set; }
public ICredentials Credentials { get; set; }
public IWebProxy Proxy { get; set; }
public HttpClient CreateHttpClient()
{
return new HttpClient(CreateHttpMessageHandler())
{
BaseAddress = this.baseAddress,
Timeout = this.Timeout,
};
}
private HttpMessageHandler CreateHttpMessageHandler()
{
return new HttpClientHandler()
{
AutomaticDecompression = System.Net.DecompressionMethods.GZip
| System.Net.DecompressionMethods.Deflate,
Credentials = this.Credentials,
PreAuthenticate = this.Credentials != null,
Proxy = this.Proxy,
UseProxy = this.Proxy != null,
};
}