[英]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
. 是的,
Response.WriteFile
终止响应,因此我可以想象您得到了ThreadAbortException
。 If you want to write the file to response and continue executing code, I recommend using one of the following 2 options: 如果要编写文件以响应并继续执行代码,建议使用以下两个选项之一:
WriteFile
to BinaryWrite
. WriteFile
更改为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. BinaryWrite
将数据写入响应。 This will not end the response and you can proceed with other code. WriteFile
until after the other "waiting" code is executed. WriteFile
推迟到执行其他“等待”代码之后。 Then return to that line of code to complete the transaction.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.