开发者

Download a file in VB.net

开发者 https://www.devze.com 2023-02-26 02:03 出处:网络
I\'m using the following code to allow users to download a file. Dim myFile As FileInfo = New FileInfo(strPath & strFile)

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.
0

精彩评论

暂无评论...
验证码 换一张
取 消