I am using FilesystemWatcher to look for newfile in the directory. The file type of investigation is .blf. It is being created of size almost 10MB (not constant but around/almost figure) Once the file is created and being written completely, i want to copy the file into someother folder. But the program immediately starts to copy even when the file is in process of being written and i get the error of "The Process cannot access the file because it is being created by another process" i want to make a condition to check if the file is completly created and then do the copy; Below is my code:
Private Sub Fsw1_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Fsw1.Created
ListBox2.Items.Add("File- " & e.FullPath.ToString & " created at: " & System.DateTime.Now)
Dim blffolder As String = String.Format("C:\Users\nha4abt\Desktop\Main\blf_files" + "\{0}", DateTime.Today.ToString("dd-MMM-yyyy"))
'Check if subfolders exists or not
If (Not System.IO.Directory.Exists(blffolder)) Then
System.IO.Directory.CreateDirectory(blffolder)
End If
'Repeat steps 1-6
Dim destPath As String = Path.Combine(blffolder, Path.GetFileName(e.FullPath))
'System.Threading.Thread.Sleep(1000)
File.Copy(e.FullPath, destPath, True) 'copy all the files in destination folder
' Compare the two files that are referenced in the textbox controls.
If (FileCompare(e.FullPath, destPath)) Then
ListBox1.Items.Add(e.FullPath & "- is correctly copied :) ") ' put all the names in listbox; Not necessary
'To Add: make a log file .txt to put the record of all the files that are copied during the process
Dim strFile As String = String.Format(DestinationDirectory + "\Log_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy")) 'create a .txt file for log
Dim texttoappend As String
Dim timedate As String
timedate = DateTime.Now
texttoappend = e.FullPath + vbCrLf + "copied to" & vbCrLf & destPath & vbCrLf & "at" & timedate + vbNewLine & vbCrLf
File.AppendAllText(strFile, String.Format(texttoappend, Environment.NewLine))
Else
MessageBox.Show("Files are not equal.")
File.Copy(e.FullPath, destPath, True) 'copy again
End If
End Sub
I tried to use System.Threading.Thread.Sleep(1000) but couldn't run the program. please guide