Srav
Srav

Reputation: 67

Response.WriteFile writing the webpage source instead of the text file

When I am trying to get a text file from shared location and when user opens it from web browser its not showing text file content and it is showing the page source. How to avoid that? What am i doing wrong? here is my code. but when i run in my local i can able to see the text file data and i am getting page source too. My English is bad sorry if there are any mistakes.

 GridViewRow rw = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
 LinkButton lnkTxtFile = (LinkButton)rw.FindControl("lnkTxtFile");
 string strFilename = lnkTxtFile.Text.Replace("/","\\");
 System.IO.FileInfo targetFile = new System.IO.FileInfo(strFilename);
 Response.Clear();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + targetFile.Name);
 Response.ContentType = "application/octet-stream";
 Response.WriteFile(targetFile.FullName);
 HttpContext.Current.ApplicationInstance.CompleteRequest();

Upvotes: 0

Views: 2984

Answers (2)

Rui Jarimba
Rui Jarimba

Reputation: 17979

Try replacing

HttpContext.Current.ApplicationInstance.CompleteRequest();

with

Response.End();

Upvotes: 0

Mike the Tike
Mike the Tike

Reputation: 1136

Change HttpContext.Current.ApplicationInstance.CompleteRequest(); to Response.End();

I suspect that CompleteRequest() is rendering the rest of the page. Response.End() closes the response stream and returns it immediately to the client.

Upvotes: 1

Related Questions