我正在尝试使用SharpZipLib创建ZIP文件并将其发送给客户端,在没有网格的页面中代码可以正常工作,并且一切正常,但是在具有网格的页面中文件总是被损坏。
我试图在ZIP文件下载方法的末尾使用HttpContext.Current.Response.End(),它确实有效,但这意味着ThreadAbortException,此后我无法再执行其他代码
这是我用来创建和下载ZIP文件的代码
Public Function ExportToZIPFile(ByVal dataTable As DataTable, orderID As Integer, downloadedZIPFileName As String, ByRef zipFilePassword As String) As Boolean
Dim isSuccess As Boolean = False
Dim excelFilePath As String = Hosting.HostingEnvironment.MapPath("~/Test.xls")
Try
Using streamWriter As StreamWriter = New StreamWriter(excelFilePath)
For i As Integer = 0 To dataTable.Columns.Count - 1
streamWriter.Write(dataTable.Columns(i).ToString().ToUpper() & vbTab)
Next
streamWriter.WriteLine()
For i As Integer = 0 To (dataTable.Rows.Count) - 1
For j As Integer = 0 To dataTable.Columns.Count - 1
If dataTable.Rows(i)(j) IsNot Nothing Then
streamWriter.Write(Convert.ToString(dataTable.Rows(i)(j)) & vbTab)
Else
streamWriter.Write(vbTab)
End If
Next
streamWriter.WriteLine()
Next
streamWriter.Close()
End Using
zipFilePassword = "123456"
SendPasswordInMessage(orderID, zipFilePassword)
HttpContext.Current.Response.ContentType = "application/x-zip-compressed"
HttpContext.Current.Response.AppendHeader("content-disposition", "attachment;filename=" + downloadedZIPFileName + ".zip")
Using zipOutput As ZipOutputStream = New ZipOutputStream(HttpContext.Current.Response.OutputStream)
zipOutput.Password = zipFilePassword
Dim ZipEntry As ZipEntry = New ZipEntry(Path.GetFileName(excelFilePath))
zipOutput.PutNextEntry(ZipEntry)
Using fread = File.OpenRead(excelFilePath)
Dim buffer As Byte() = New Byte(8191) {}
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fread, zipOutput, buffer)
End Using
zipOutput.Finish()
End Using
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
isSuccess = True
Catch tah As ThreadAbortException
Catch ex As Exception
MStartLogger.Error(ex, Me.GetType.Name, MethodBase.GetCurrentMethod().Name, "")
Finally
If File.Exists(excelFilePath) Then
File.Delete(excelFilePath)
End If
End Try
Return isSuccess
End Function
我认为问题在于HttpContext.Current.Response没有花时间创建文件并下载它,因此我希望创建ZIP文件下载并返回成功消息并返回到我之前的代码
答案 0 :(得分:0)
我认为问题在于这行将缓冲区数组限制为8191
Dim buffer As Byte() = New Byte(8191) {}
我建议将其更改为类似
Dim buffer As Byte() = New Byte(fread.length) {}