views:

52

answers:

2

I'm creating a csv file on the fly in my ASP.NET web app and sending it back to the user using the following code

ExportPlacementListPostModel postModel = CreatePostModelFromRequest();
MemoryStream stream = PlacementDatabaseController.ExportPlacementList(postModel);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment; filename=studentplacement.csv");
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(stream.GetBuffer());

Every time I download the file the web pages html is being appended onto the document.

Can anyone see what i am doing wrong here.

Colin G

+2  A: 

Call Response.End() after Response.BinaryWrite to prevent further output being written to the response.

pmarflee
The Response.End() answer from pmarflee is probably appropriate, but I believe you can also do: return;
Iain Collins
+1  A: 

HttpContext.Current.ApplicationInstance.CompleteRequest can be used as well.

The CompleteRequest method causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.

The Response.End method ends the page execution and shifts the execution to the Application EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

Here's a good read: Don’t use Response.End() with OutputCache

o.k.w