0

我正在使用下面的代码尝试打开 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()
4

3 回答 3

2

您需要拥有fs在 using 内部引用的所有代码,否则您将尝试访问已被释放的对象。我也会对 做同样的事情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
...
于 2013-07-23T18:07:53.653 回答
1

您有以下几行:

Using (fs)

End Using

结束使用后,关闭文件并处理 fs 对象。

您需要将从 fs 读取的代码放入 using 块中。

于 2013-07-23T18:08:10.083 回答
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
于 2013-07-23T18:08:36.477 回答