2016-06-16 6 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

関連する問題