Magnus Magnus - 5 months ago 40
Vb.net Question

Getting Cannot access a closed file error

I use the following code to iterate a collection of files that I need to copy from one folder to another. It works fine when the source file exist, but when it does not exist I get


System.ObjectDisposedException: Cannot access a closed file. at System.IO.__Error.FileNotOpen() at System.IO.FileStream.get_Position()


What am I missing here?

For Each itm In listOfFiles
Try
If File.Exists(itm.SourcePath + itm.FileName) Then

Dim cf As New FileStream(itm.SourcePath + itm.FileName, FileMode.Open)
Dim ct As New FileStream(itm.DestinationPath + itm.FileName, FileMode.Create)
Dim len As Long = cf.Length - 1
Dim buffer(1024) As Byte
Dim byteCFead As Integer
While cf.Position < len
byteCFead = (cf.Read(buffer, 0, 1024))
ct.Write(buffer, 0, byteCFead)
fileCopyProgressBar.BeginInvoke(New Action(Sub() fileCopyProgressBar.Value = CInt(cf.Position / len * 100)))

End While
ct.Flush()
ct.Close()
cf.Close()

itm.FileExsits = True

Else
itm.FileExsits = False
End If

Catch ex As Exception
log.Error(ex.Message & " (unc)")
End Try
Next

Answer

Try calculating value before putting it in the action. You should also dispose of the streams when done with them

For Each itm In listOfFiles
    Try
        If File.Exists(itm.SourcePath + itm.FileName) Then
            Using cf As New FileStream(itm.SourcePath + itm.FileName, FileMode.Open)
                Using ct As New FileStream(itm.DestinationPath + itm.FileName, FileMode.Create)
                    Dim len As Long = cf.Length - 1
                    Dim buffer(1024) As Byte
                    Dim byteCFead As Integer
                    Dim percentage As Integer
                    While cf.Position < len
                        byteCFead =(cf.Read(buffer, 0, 1024))
                        ct.Write(buffer, 0, byteCFead)
                        percentage = CInt(cf.Position / len * 100)
                        fileCopyProgressBar.BeginInvoke(New Action(Sub() fileCopyProgressBar.Value = percentage))
                    End While

                    ct.Flush()
                    ct.Close()
                    cf.Close()
                End Using
            End Using

            itm.FileExsits = True
        Else
            itm.FileExsits = False
        End If
    Catch ex As Exception
        log.Error(ex.Message & "  (unc)")
    End Try
Next
Comments