Alex Alex - 3 months ago 35
Vb.net Question

Progress Bar for Directory copy(including subdirectories)

I think im stuck with a wrong approach to a problem. Im trying to get a reliable progress bar for copying files to an USB-Drive. My Problem is that with my approach, it will work but not reliable show the necessary information, as the file created event will trigger way before the file has completed to write ( and in case of directory copy, its multithreated and will create almost all files immediately but will write for far far longer especially if the usb dirve is slow (usb 2.0). Below is my approach, but I'm sure there must be a better way to solve this problem.

Public counterLocalFiles As String
Private Sub CopyUSB
fsw_USB = New IO.FileSystemWatcher(Path)
fsw_USB.IncludeSubdirectories = True
fsw_USB.EnableRaisingEvents = True
UpdateProgressBarMaximum2(CInt(counterLocalFiles))
counterLocalFiles = System.IO.Directory.GetFiles(SourcePath,
My.Computer.FileSystem.CopyDirectory(SourcePath, Path)"*.jpg*", SearchOption.AllDirectories).Length
End Sub

Private Sub fsw_USB_Created(sender As Object, e As FileSystemEventArgs) Handles fsw_USB.Created
Dim counterUSBFiles = IO.Directory.GetFiles(Path, "*.jpg", SearchOption.AllDirectories).Length
UpdateProgressBar2(CInt(counterUSBFiles))
UpdateLabelText2(CStr(counterUSBFiles) & " von " & CStr(counterLocalFiles))
End Sub

Private Sub UpdateProgressBarMaximum2(Maximum As Int32)
If ProgressBar2.InvokeRequired Then
ProgressBar2.Invoke(New Action(Of Integer)(AddressOf UpdateProgressBarMaximum2), Maximum)
Else
'We are on the UI thread so update the control.
ProgressBar2.Maximum = Maximum
End If
End Sub

Private Sub UpdateProgressBar2(Value As Int32)
If ProgressBar2.InvokeRequired Then
ProgressBar2.Invoke(New Action(Of Integer)(AddressOf UpdateProgressBar2), Value)
Else
'We are on the UI thread so update the control.
ProgressBar2.Value = Value
End If
End Sub

Answer

I created an example of how to do it using a BackgroundWorker and FileStream. The code is more than I can post here...because it's a Visual Studio project...so I've zipped it up and you can download it here: http://www.filedropper.com/copydirectoryvisualstudioexample

You can run it and select Source and Destination folders.

The main directory copy process happens in bgwDirectoryCopy_DoWork and the individual file copy process happens in copyFileWithProgress

Just modify however you need...right now it copies *.*

Comments