IEnumerable<string> to Stream for FileStreamResult

狂风中的少年 提交于 2019-12-30 10:44:24

问题


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?

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.

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.


回答1:


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);
            }
        }
    }
}



回答2:


I think you can use it in this first convert your string to byte array and use memory stram afterwards

string sourceFile = System.Web.HttpContext.Current.Server.MapPath(Path.Combine("/", "yourAddress"));
byte[] byteArray = System.IO.File.ReadAllBytes(sourceFile);

MemoryStream mem;
        using (mem = new MemoryStream())
        {
            mem.Write(byteArray, 0, (int)byteArray.Length);
            return mem;
        }


来源:https://stackoverflow.com/questions/22830393/ienumerablestring-to-stream-for-filestreamresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!