2016-06-16 3 views
-1

다음 코드를 사용하여 한 폴더에서 다른 폴더로 복사해야하는 파일 컬렉션을 반복합니다. 원본 파일이있을 때 제대로 작동하지만 존재하지 않을 때닫힌 파일에 액세스 할 수 없음 오류가 발생했습니다.

System.ObjectDisposedException : 닫힌 파일에 액세스 할 수 없습니다. at System.IO.__ Error.FileNotOpen() at 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 
+2

어디에서 폐기할까요? –

+0

이것은 응용 프로그램을 실행하는 서버에서받는 오류입니다. System.ObjectDisposedException : 닫힌 파일에 액세스 할 수 없습니다. at System.IO .__ Error.FileNotOpen() at System.IO.FileStream.get_Position() – MTplus

+1

어떤 줄 번호? –

답변

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 
+0

그 트릭을 했어, 고마워! – MTplus