Click here to Skip to main content
15,850,298 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
hi i have a webpage in my application that allows users to download a file.
for that i hv written the following code:
VB
Dim fullpath As String = filename


       Dim name = Path.GetFileName(fullpath)
       Dim ext = Path.GetExtension(fullpath)
       Dim type As String = ""
       Try
           If Not IsDBNull(ext) Then
               ext = LCase(ext)
           End If
           Select Case ext
               Case ".txt"
                   type = "text/plain"
               Case ".doc", ".rtf"
                   type = "Application/msword"
               Case Else
                   type = "text/plain"
           End Select
           If (forceDownload) Then  
               Response.AppendHeader("content-disposition", _
               "attachment; filename=" + name)
           End If
           If type <> "" Then
               Response.ContentType = type 
           End If
           Response.WriteFile(fullpath) 
           Response.End() 'creates an property evaluation failed exception

this code works fine ..but response.end() raises an ThreadAbortException.
also if i use HttpContext.Current.ApplicationInstance.CompleteRequest() or response.flush()
then the htmlcode of the current page also comes in the downloaded file.

can anyone suggest me an alternative


i also want to delete the file from the server as soon as it is downloaded.
for this i tried writing the
file.delete(filepath)

but if it is written before response.end the page keeps on processing and no dialog box appears.
if i write it after response.end it is not executed since the execution of the page ends.

can any one suggest something...

thanks in advance
Posted
Updated 7-Feb-11 3:44am
v3

1 solution

I always found automated file downloads in ASP.net work best with this content type declaration:

Response.ContentType = "application/octet-stream"


as for your second question, you could remove:

Response.WriteFile(fullpath) 


from your code altogether and replace it with code that writes the byte[] array of the file into the OutputStream property:

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.outputstream.aspx[^]

after you've written to the OutputStream, you can do your file cleanup before you finalize the response.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900