简体   繁体   中英

Download a file in VB.net

I'm using the following code to allow users to download a file.

Dim myFile As FileInfo = New FileInfo(strPath & strFile)
Response.AddHeader("Content-Disposition", "attachment; filename=" & _
Replace(myFile.Name, ".resources", ""))
Response.AddHeader("Content-Length", myFile.Length.ToString())
Response.ContentType = "application/octet-stream"
Response.WriteFile(myFile.FullName)

This method has the annoying problem that any code after this line does not execute correctly.

It pretty ancient code, so I'm guessing there are probably better ways to do this these days. Can anyone suggest one?

Yes, Response.WriteFile terminates the response when it's done, so I would imagine you get a ThreadAbortException . If you want to write the file to response and continue executing code, I recommend using one of the following 2 options:

  1. Change from WriteFile to BinaryWrite . Use a StreamReader to get the contents of the file into a byte array, and use BinaryWrite to write that data to the response. This will not end the response and you can proceed with other code.
  2. Postpone the WriteFile until after the other "waiting" code is executed. Then return to that line of code to complete the transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM