0

I am attempting to write content to a Response output stream.

The idea is that a user clicks a link and is prompted to save a file to their machine.

The user is prompted and the info is written successfully, but appended on to the end of the file is the rendered html of the page that launched the event. Why would html be appended on to my closed stream?

First I grab my stream, this happens in the click event of a link:

Response.ClearContent();
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + exportType + ".txt\"");
Response.BufferOutput = true;
using (var stream = Response.OutputStream)
{
    ExportService.ExportPurchaseOrder(exportType, stream, PoList);
}

I pass the stream around a bit (var name becoming outputStream), but ultimately write it like this:

using (var output = new StreamWriter(outputStream))
{
    var lineLength = positions.Last().Start + positions.Last().Length;
    var line = new StringBuilder(lineLength);
    foreach (var field in positions)
    {
        line.Insert(field.Start, FormatFixedValue(field, data));
    }
    output.WriteLine(line.ToString());
    output.Flush();
}

Is there any reason why I should still see output like this?

L20110              5001638088169                                      00000000008000000720000                         EACH 
L20110              6001638088152                                      00000000008000001020000                         EACH


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"> <head><title>

...
crthompson
  • 15,653
  • 6
  • 58
  • 80
  • 1
    You continue to render your page. There are many similar questions - you need to stop processing request (or if using ASP.Net MVC simply return `FileResult` ). [Is Repsonse.End considered harmful](http://stackoverflow.com/questions/1087777/is-response-end-considered-harmful) contains all info you need to fix it. – Alexei Levenkov Jul 15 '14 at 14:54
  • @AlexeiLevenkov, I figured there were similar questions, but i could not find any. It was difficult to come up with the terms to explain what i'm doing. – crthompson Jul 15 '14 at 14:58
  • @AlexeiLevenkov, thank you for the suggestion, I did have close in there, but figured the using was better code and did the closing for you. Is this not correct? – crthompson Jul 15 '14 at 14:58
  • Sorry - you indeed have `using` that should have closed the stream directly/via writer... I'm not sure why closing response stream is not enough, but I'd follow recommendations in post I've suggested above to fix it. – Alexei Levenkov Jul 15 '14 at 15:02
  • @AlexeiLevenkov, its the perfect answer, and it works a treat. I'm sure this could be marked a dupe then. Thanks – crthompson Jul 15 '14 at 15:05

0 Answers0