views:

265

answers:

6

When I try to redirect to a new page after downloading a file it doesn't work. Do I have to remove or modify anything in this code? the debugger doesnt reach it

byte[] fileData = (byte[])sqlRead[3];

Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=" + sqlRead[2]);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(fileData);

Response.Flush();
Response.End();
Response.Clear();

Response.Redirect("Questions.aspx");
+3  A: 

Take out

Response.End();

Response.End kills the entire response, nothing after that will run.

The End method causes the Web server to stop processing the script and return the current result. The remaining contents of the file are not processed.

Andrew Hare
i removed it but now i got this exception:Cannot redirect after HTTP headers have been sent
Ahmad Farid
Ah that is true. Since ASP.NET uses the headers to redirect the user you won't be able to `Response.Redirect` in this way. I would suggest that you take Steven's advice (http://stackoverflow.com/questions/1244621/directing-to-a-new-page-after-downloading-a-file/1244705#1244705) and use javascript to redirect the user.
Andrew Hare
A: 

I'm not ASP guy, but you also need to move the Redirect call above any call that writes something to the body of the response.

Try to put the Redirect() call right after Response.Clear()

The redirect URL is transferred in header of HTTP response, thus calling it afterwards the body was generated (and thus the header was already generated and sent) would render in no effect or an error.

david a.
i already did taht!!
Ahmad Farid
A: 

Do not use the response.end()/ It will abruptly end the request processing thread.

deostroll
when i remove it i get an exception
Ahmad Farid
+1  A: 

Andrew is right about Response.End stopping execution. I don't think that removing it will help, though, since it would just affect the file you're sending.

You can get the effect you want with other tricks. For example, you could use some JS on the page with the DL link to do a client-side redirect.

edit

What I'm suggesting is that you add a secondary behavior to your download link so that clicking on it both downloads the file and changes the current page. It might work better if clicking starts a timer that does the redirect in a second or so.

Steven Sudit
A: 

You could try removing this whole block:

Response.Flush();
Response.End();
Response.Clear();

I think the problem might be that the call to Flush() is causing content to be sent to the browser, so it is then too late to add the redirect HTTP headers that get added when you call Redirect().

HullCitySteve
when i remove them all, the redirection works but the download doesnt work!!
Ahmad Farid
A: 

I solved that but I forgot how it was. Ask me if you are interested and I could look through.

Ahmad Farid