我正在使用下面的代码尝试打开pdf文件而我收到的错误无法打开已关闭的文件?不知道我在这里缺少什么。
Dim FileName As String
Dim FolderLocation As String = Nothing
Dim FileFormat As String = "application/pdf"
Dim tFileNameArray As Array = Nothing
Dim tFileName As String = Nothing
FileName = "\\Server\Files\45144584.pdf"
Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read)
Using (fs)
End Using
Dim data() As Byte = New Byte(fs.Length) {}
Dim br As BinaryReader = New BinaryReader(fs)
br.Read(data, 0, data.Length)
br.Close()
Response.Clear()
Response.ContentType = FileFormat
Response.AppendHeader("Content-Disposition", "attachment; filename=" & tFileName.Split("\")(tFileName.Split("\").Length - 1))
Response.BufferOutput = True
Response.BinaryWrite(data)
Response.End()
答案 0 :(得分:2)
您需要在使用中包含引用fs
的所有代码,否则您将尝试访问已经处置的对象。我也会对BinaryReader
做同样的事情,因为它也实现了IDisposable
:
Dim data() As Byte
Using fs As New FileStream(FileName, FileMode.Open, FileAccess.Read)
data = New Byte(fs.Length) {}
Using br As New BinaryReader(fs)
br.Read(data, 0, data.Length)
End Using
End Using
...
答案 1 :(得分:1)
您有以下几行:
Using (fs)
End Using
结束使用后,文件关闭,fs对象被处理掉。
您需要将使用fs读取的代码放在using块中。
答案 2 :(得分:1)
Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read)
Using (fs)
End Using
Dim data() As Byte = New Byte(fs.Length) {}
...
您在处置后尝试使用fs
。这需要:
Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read)
Using (fs)
Dim data() As Byte = New Byte(fs.Length) {}
Dim br As BinaryReader = New BinaryReader(fs)
br.Read(data, 0, data.Length)
br.Close()
End Using