Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable<string> to Stream for FileStreamResult

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.

like image 345
Matthias Avatar asked Sep 04 '25 17:09

Matthias


1 Answers

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);
            }
        }
    }
}
like image 145
Aik Avatar answered Sep 07 '25 12:09

Aik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!