我正在使用vb.net开发一个asp.net webforms网站。在gridview中显示为链接的文件列表中,单击链接时,它会调用OpenFile方法。我在网上找到的这个代码用于将存储在webserver中的文件下载到客户端,这适用于图像,但是当我尝试下载.docx或.xlsx文件时,它会出错
在"Response.BinaryWrite(btFile)"
行,但下载文件。下面给出的是实际代码的短版本
页码:
Protected Sub grvItemAttachments_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvItemAttachments.RowCommand
Try
If e.CommandName = "Open" Then
FileOpener.OpenFile(fileNameWithPath)
End If
Catch ex As Exception
ErrHandler.WriteError(ex.Message)
End Try
End Sub
文件打开器代码:
Public Shared Sub OpenFile(fileNameWithPath as string)
Dim file As New FileInfo(fileNameWithPath)
Dim fs As System.IO.FileStream = Nothing
fs = System.IO.File.Open(fileNameWithPath, System.IO.FileMode.Open)
Dim btFile As Byte() = New Byte(fs.Length - 1) {}
fs.Read(btFile, 0, Convert.ToInt32(fs.Length))
fs.Close()
Response.AddHeader("Content-disposition", "attachment; filename=" & FileName)
Response.ContentType = GetFileType(file.Extension.ToLower())
Response.BinaryWrite(btFile)
Response.End()
End Sub
错误讯息:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values." & vbCrLf & "Parameter name: offset" & vbCrLf & " at System.Web.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 count)" & vbCrLf & " at System.Web.HttpResponse.BinaryWrite(Byte[] buffer)" & vbCrLf & " at FileOpener.OpenFile(String FileName, String FolderName) in D:\Projects\VSS Projects\PIL WebSite\App_Code\Common\FileOpener.vb:line 25" & vbCrLf & " at Web_RTOView.grvItemAttachments_RowCommand(Object sender, GridViewCommandEventArgs e) in D:\Projects\VSS Projects\PIL WebSite\Web\RTOView.aspx.vb:line 310}
------
grvItemAttachments_RowCommand
Error Message: Specified argument was out of the range of valid values.
Parameter name: offset
知道如何解决这个问题吗?
答案 0 :(得分:1)
为什么要将字节数组初始化为Length-1
?不应该是长度的确切大小?
实际上,您尝试将文件的内容从0读取到Length但您的字节数组length
为Length-1