webforms getting html in my excel file Response.OutputStream

Viewed 312

I'm returning a file stream from an S3 file. Since the stream is not seekable, I place it into a MemoryStream to get the length. The file does download to the browser. When I open the file I see the correct csv data, but it also has the page HTML after the data. Not sure what I'm missing.

var streamResult = FileStream(bucket, fileName);

if (streamResult.Stream != null)
{
    //using (StreamReader reader = new StreamReader(streamResult.Stream))
    //using (Stream stream = streamResult.Stream)
    using (var ms = new MemoryStream())
    {
        streamResult.Stream.CopyTo(ms);
        ms.Position = 0;

        //byte[] bytes = System.Text.Encoding.UTF8.GetBytes(ms);

        HttpContext context = HttpContext.Current;
        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + returnFileName);
        context.Response.AddHeader("Content-Type", "application/vnd.ms-excel");
        context.Response.AddHeader("Content-Length", ms.Length.ToString());
        //context.Response.ContentType = "application/octet-stream";
        //context.Response.ClearContent();
        ms.WriteTo(context.Response.OutputStream);
        //context.Response.OutputStream.Write(bytes, 0, bytes.Length);
    }
}
1 Answers

Update: just add context.Response.Flush(); after the ms.WriteTo(context.Response.OutputStream);

Related