0

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();
Srav
  • 59
  • 3
  • 7

2 Answers2

1

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.

Mike the Tike
  • 1,136
  • 8
  • 9
  • if i do that I am getting exception "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack." But its working. How to avoid that exception? – Srav Feb 06 '13 at 15:53
0

Try replacing

HttpContext.Current.ApplicationInstance.CompleteRequest();

with

Response.End();
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
  • if i do that I am getting exception "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack." But its working. How to avoid that exception? – Srav Feb 06 '13 at 15:50
  • when i debug it its working fine i mean i can open the file but when i deployed it its not working. Do you have any idea? – Srav Feb 06 '13 at 19:33
  • Add logging to the code, and log the exception being thrown (if any). Check permissions, the paths to the downloadable files, etc – Rui Jarimba Feb 06 '13 at 19:37
  • I am getting below exception. System.Web.HttpResponse.WriteFile(String filename) at Configs.gvConfigs_RowCommand(Object sender, GridViewCommandEventArgs e) in C:\Users\bpucha1103c\Desktop\CellBackHaul_Publish\Configs.aspx.cs:line 59 2013-02-05 13:31:21,412 [19] WARN System.Web.UI.Page [(null)] - Logging:System.IO.IOException: The account used is a computer account. Use your global user account or local user account to access this server. – Srav Feb 07 '13 at 14:17
  • 1
    It seems that the user account you're using in production doesn't have the permissions to access the server where you have your files. When you fix the permissions error everything will work fine. Don't forget to upvote my answer if it was helpful, and mark one of the answers as the correct answer. – Rui Jarimba Feb 07 '13 at 14:25