Search code examples
c#response.write

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();

Solution

  • Try replacing

    HttpContext.Current.ApplicationInstance.CompleteRequest();
    

    with

    Response.End();