Solved

copy large directory fails with visual basic .net 2.0

Posted on 2012-12-27
8
384 Views
Last Modified: 2012-12-28
My.Computer.FileSystem.CopyDirectory("C:\Temp\jre1.6.0_30", "\\" & strWorkstationFQDN & "\c$\Program Files\Java\jre1.6.0_30", True)

My issue is that some the copies are on a slow network and my app crashes with the pumping error.  This happens if the copy takes longer than 60 seconds.  Anyway to fix this?
0
Comment
Question by:chadmanvb
  • 5
  • 3
8 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 38725490
Fork this work off to a new thread, and keep it off the main UI thread.

e.g.

Imports System.Threading

Public Class Form1
    Private strWorkstationFQDN As String = "localhost"

    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
        Dim copyThread As New Thread(New ParameterizedThreadStart(AddressOf DoCopy))
        Dim paths(1) As String

        paths(0) = "C:\Temp\jre1.6.0_30"
        paths(1) = "\\" & strWorkstationFQDN & "\c$\Program Files\Java\jre1.6.0_30"

        copyThread.Start(paths)
    End Sub

    Private Sub DoCopy(ByVal threadParam As Object)
        Dim paths() As String = DirectCast(threadParam, String())

        My.Computer.FileSystem.CopyDirectory(paths(0), paths(1), True)
    End Sub
End Class

Open in new window


If you require notification that the task has completed, then you might prefer the BackgroundWorker class instead.
0
 

Author Comment

by:chadmanvb
ID: 38725592
I tried that, but I still get an error.  If I manually copy the files it works fine.  It does prompt me to overwrite the files.

error=Could not complete operation on some files and directories. See the Data property of the exception for more details.

 Private Sub DoCopy(ByVal threadParam As Object)
        Dim paths() As String = DirectCast(threadParam, String())
        Try
            My.Computer.FileSystem.CopyDirectory(paths(0), paths(1), True)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub
0
 

Author Comment

by:chadmanvb
ID: 38725598
also could it show the copyui, prograss bar? as it does the copy?
0
 

Author Comment

by:chadmanvb
ID: 38725600
Also, I would like to know if all the copies completed without an error.  I have about 300 copies to make.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 38725604
also could it show the copyui, prograss bar? as it does the copy?
For that, you are going to need a different approach.

What kind of exception is generated?
0
 

Author Comment

by:chadmanvb
ID: 38725615
dont have to have the ui, but would like to know that all the copies completed.  

   at Microsoft.VisualBasic.FileIO.FileSystem.FxCopyOrMoveDirectory(CopyOrMove operation, String sourceDirectoryPath, String targetDirectoryPath, Boolean overwrite)
   at Microsoft.VisualBasic.FileIO.FileSystem.CopyOrMoveDirectory(CopyOrMove operation, String sourceDirectoryName, String destinationDirectoryName, Boolean overwrite, UIOptionInternal showUI, UICancelOption onUserCancel)
   at Microsoft.VisualBasic.MyServices.FileSystemProxy.CopyDirectory(String sourceDirectoryName, String destinationDirectoryName, Boolean overwrite)
   at Chadware.Form1.DoCopy(Object threadParam) in C:\Temp\practicevb\NEWSQL\EasyButton2\EasyButton2\Form1.vb:line 4982
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart(Object obj)
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 38725830
Try this approach:

Imports System.IO

Public Class Form1
    Private strWorkstationFQDN As String = "localhost"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.bwCopy.WorkerSupportsCancellation = True
        Me.bwCopy.WorkerReportsProgress = True
        Me.pbCopy.Minimum = 0
    End Sub

    Private Sub bwCopy_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwCopy.RunWorkerCompleted
        Dim failedCopies As List(Of String) = DirectCast(e.Result, List(Of String))

        For Each failed As String In failedCopies   '''''''''''''''''''''''''''''''
            MessageBox.Show(failed)                 '  CHANGE THIS!!!!
        Next                                        '''''''''''''''''''''''''''''''

        Me.btnCopy.Enabled = True
    End Sub

    Private Sub btnCopy_Click(sender As Object, e As EventArgs) Handles btnCopy.Click
        Dim paths(1) As String

        paths(0) = "C:\Windows\Microsoft.NET"
        paths(1) = "D:\test"

        Me.btnCopy.Enabled = False
        Me.bwCopy.RunWorkerAsync(paths)
    End Sub

    Private Sub SetProgressBarMaximum(ByVal maximum As Integer)
        If Me.pbCopy.InvokeRequired Then
            Me.pbCopy.Invoke(New Action(Of Integer)(AddressOf SetProgressBarMaximum), maximum)
        Else
            Me.pbCopy.Maximum = maximum
        End If
    End Sub

    Private Sub bwCopy_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwCopy.DoWork
        Dim paths() As String = DirectCast(e.Argument, String())
        Dim totalFiles As Integer = GetFileCount(paths(0))

        SetProgressBarMaximum(totalFiles)
        e.Result = CopyFiles(paths(0), paths(1), totalFiles)
    End Sub

    Private Sub bwCopy_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bwCopy.ProgressChanged
        Me.pbCopy.Value += e.ProgressPercentage
    End Sub

    Private Function GetFileCount(ByVal path As String) As Integer
        Dim result As Integer = 0
        Dim folderStack As New Stack(Of String)

        folderStack.Push(path)

        While folderStack.Count > 0
            Dim folder As String = folderStack.Pop()

            result += Directory.GetFiles(folder).Length

            For Each subfolder As String In Directory.GetDirectories(folder)
                folderStack.Push(subfolder)
            Next
        End While

        Return result
    End Function

    Private Function CopyFiles(ByVal source As String, ByVal target As String, ByVal fileCount As Integer) As List(Of String)
        Dim folderStack As New Stack(Of String)
        Dim failedCopies As New List(Of String)()

        folderStack.Push(source)

        While folderStack.Count > 0
            Dim srcfolder As String = folderStack.Pop()
            Dim trgFolder As String = Path.Combine(target, srcfolder.Replace(source, ""))

            If Not Directory.Exists(trgFolder) Then
                Directory.CreateDirectory(trgFolder)
            End If

            For Each srcFile As String In Directory.GetFiles(srcfolder)
                Dim trgFile As String = Path.Combine(trgFolder, Path.GetFileName(srcFile))

                Try
                    File.Copy(srcFile, trgFile)
                Catch ex As Exception
                    failedCopies.Add(srcFile)
                End Try

                Me.bwCopy.ReportProgress(1)
            Next

            For Each subfolder As String In Directory.GetDirectories(srcfolder)
                folderStack.Push(subfolder)
            Next
        End While

        Return failedCopies
    End Function
End Class

Open in new window


You would need to add a BackgroundWorker (on the "Components" tab) and a ProgressBar to your form. Change the file paths accordingly, and be sure to change the MessageBox code. (You probably don't want to click through 100 dialog boxes if 100 files fail to copy!)
0
 

Author Closing Comment

by:chadmanvb
ID: 38727247
perfect
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now