Solved

copy large directory fails with visual basic .net 2.0

Posted on 2012-12-27
8
413 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
8 Comments
 
LVL 75

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
Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

 

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
 
LVL 75

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 75

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

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

688 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