获取无法访问已关闭的文件错误

时间:2016-06-16 10:35:51

标签: vb.net filestream

我使用以下代码迭代我需要从一个文件夹复制到另一个文件夹的文件集合。它在源文件存在时工作正常,但是当它不存在时我得到

  

System.ObjectDisposedException:无法访问已关闭的文件。在System.IO .__ Error.FileNotOpen()在System.IO.FileStream.get_Position()

我在这里缺少什么?

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

1 个答案:

答案 0 :(得分:1)

在将其放入动作之前尝试计算值。你也应该在完成这些流后处理它们

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