user1342164
user1342164

Reputation: 1454

Cant open a closed file

I am using the code below to try and open a pdf file and I am getting the error cannot open a closed file? Not sure what I am missing here.

    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()

Upvotes: 0

Views: 205

Answers (3)

user47589
user47589

Reputation:

Dim fs As New FileStream(FileName, FileMode.Open, FileAccess.Read)
Using (fs)

End Using
Dim data() As Byte = New Byte(fs.Length) {}
...

You're trying to use fs after it has been disposed. This needs to be:

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

Upvotes: 1

Tombala
Tombala

Reputation: 1690

You have the following lines:

Using (fs)

End Using

After End Using, the file is closed and the fs object disposed of.

You need to put the code that reads from fs inside the using block.

Upvotes: 1

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

You need to have all code that references fs inside of the using, otherwise you are attempting to access an object that has already been disposed. I would also do the same thing with the BinaryReader, since it also implements 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
...

Upvotes: 2

Related Questions