IEnumerable< string>流以获取FileStreamResult [英] IEnumerable<string> to Stream for FileStreamResult
问题描述
我有一个 IEnumerable< string>
,它是根据方法中的每个 yield
语句流式传输的。现在,我想将此可枚举转换为 Stream
以将其用作流式结果。有什么想法可以做到吗?
I have an IEnumerable<string>
, which is "streamed" per yield
statements from a method. Now I want to convert this enumerable to a Stream
to use it as streamed result. Any ideas how I can do this?
我最后要做的就是将 Stream
返回为 FileStreamResult
来自ASP.NET控制器操作。此结果应作为下载流式传输到客户端。
What I finally want to do is to return the Stream
as FileStreamResult
from an ASP.NET controller action. This result should be streamed as download to the client.
我不想做的是写 IEnumerable的全部内容
到流中,然后返回结果。
What I do NOT want to do is to write the whole content of the IEnumerable
to the stream before I return the result. This would eliminate the whole sense of the streaming concept.
推荐答案
您必须创建ActionResult类以实现惰性评估。您已经创建了 ContentResult
和 FileStreamResult
类的混合,以实现类似于FileStreamResult的行为并具有设置结果编码的能力。好的起点是 FileResult
抽象类:
You have to create your ActionResult class to achieve lazy evaluation. You have create mix of ContentResult
an FileStreamResult
classes to achieve behaviour like FileStreamResult with ability to set result encoding. Good starting point is FileResult
abstract class:
public class EnumerableStreamResult : FileResult
{
public IEnumerable<string> Enumerable
{
get;
private set;
}
public Encoding ContentEncoding
{
get;
set;
}
public EnumerableStreamResult(IEnumerable<string> enumerable, string contentType)
: base(contentType)
{
if (enumerable == null)
{
throw new ArgumentNullException("enumerable");
}
this.Enumerable = enumerable;
}
protected override void WriteFile(HttpResponseBase response)
{
Stream outputStream = response.OutputStream;
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Enumerable != null)
{
foreach (var item in Enumerable)
{
//do your stuff here
response.Write(item);
}
}
}
}
这篇关于IEnumerable< string>流以获取FileStreamResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!