How to Copy a directory and all its contents

This question is a recreation of the original question. There were several valid answers and the originlal was deleted in order to propagate the points out to the Experts that assisted.


-----original question text------

From: brockway Date: Wednesday, June 23 1999 - 09:20AM CDT  
Status: Answered.This question is locked until brockway evaluates the answer.
Points: 250 Points
Anybody know how to copy (Duplicate) a directory and all its files and subdirectories?  I know about the SHFileOperation API but this adds a directory structure under the new name. For example say I want to make a duplicate of C:\Windows as C:\Windows2. SHFileOperation creates C:\Windows2 then hangs C:\Windows under C:\Windows2 thus:

+   Windows
         + Subdir1
         + SubDir2

Whereas wha I'm looking for is:

    +  subdir1
    +  subdir2

Essentrially copying the content of the source directory under the new directory.

Any thoughts


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

darinwAuthor Commented:
Rejected Answer
From: jbil Date: Wednesday, June 23 1999 - 09:39AM CDT  
add msscripting runtime in proj references.
and code like this...

Private Sub Form_Click()
Dim fso As New FileSystemObject, drv As Drive, s As String
fso.CopyFolder "C:\WINDOWS\Desktop\New Folder", "C:\WINDOWS\Desktop\New Folder2"
End Sub

From: brockway Date: Wednesday, June 23 1999 - 12:39PM CDT  
Sorry I should have mentioned I'm using Visual Basic 5 and I'm not sure if Visual Script functions like FileSystemObject are available to VB5.

When attempting the code suggested I get "FileSystemObject user defined object not defined".

Sorry to be so dumb but is this possilble in VB5?


Rejected Answer
From: dhwanilshah Date: Wednesday, June 23 1999 - 01:02PM CDT  
I think it is possible.

I think that u didnt add the refrence to the scripting library before writing the above code.

File System Object works with ASP as well as far as I can see VB 5.0 also.

Try adding the Microsoft Runtime Scripting Library first.

From: waty Date: Wednesday, June 23 1999 - 01:04PM CDT  
Take a look here :

From: brockway Date: Wednesday, June 23 1999 - 01:55PM CDT  
For  JBil & Dhwanilshah: I'm sorry I'm just not seeing anything like "Microsoft Runtime Scripting Library" or "msscripting" in my project reference options. I think it possible I don't have VBScript installed. In fact to be honest I'm not sure what VBScript is or how it fits in. I'd really like to get this to work. It's so much simpler that the complicated recursive code I've had to write to copy subdirectories. This API code of mine works but, like I say, something simpler like the .CopyFolder method would be a lot better.

For Waty: Thanks for the idea, but the  API example only copies files at one level. I've already written code that calls itself recursively to deal with subdirectories but I was hoping for something a little simpler.

Thanks for the help


From: jbil Date: Wednesday, June 23 1999 - 09:31PM CDT  
check in your c/windows/system for this file, if it's there
should be able to add to references and use filescriptobject. w / vb5 or vb6


Rejected Answer
From: kfrick Date: Wednesday, June 23 1999 - 10:18PM CDT  
I know lots of folks don't like it, but have you considered shelling out to DOS?

The xcopy command can copy directories as you describe.....try this:

Sub CopyWindows
  Shell "xcopy Windows Windows2 /s /i"
End Sub

hope this helps!


From: waty Date: Thursday, June 24 1999 - 03:49AM CDT  
Here is the XCopy in VB :

' #VBIDEUtils#************************************************************
' * Programmer Name  : Waty Thierry
' * Web Site         : 
' * E-Mail           :
' * Date             : 27/04/99
' * Time             : 14:26
' **********************************************************************
' * Comments         : Mimic the XCopy
' *
' *
' **********************************************************************

Function CopyFiles(srcPath As String, dstPath As String, IncludeSubDirs As Integer, FilePat As String, Frm_Copy As Form) As Integer
   ' #VBIDEUtils#************************************************************
   ' * Programmer Name  : Waty Thierry
   ' * Web Site         : 
   ' * E-Mail           :
   ' * Date             : 4/03/99
   ' * Time             : 17:06
   ' * Module Name      : Form1
   ' * Module Filename  :
   ' * Procedure Name   : CopyFiles
   ' * Parameters       :
   ' *                    srcPath As String
   ' *                    dstPath As String
   ' *                    IncludeSubDirs As Integer
   ' *                    FilePat As String
   ' **********************************************************************
   ' * Comments         :
   ' * This routine copies all files matching FilePat from scrPath to dstPath.
   ' * If IncludeSubDirs is set to True, all files in subdirs will be incuded (and
   ' * the subdirs themselves of course), like XCOPY /S
   ' *
   ' *
   ' **********************************************************************
   Const ATTR_DIRECTORY = 16
   Dim DirOK         As Integer
   Dim i             As Integer
   Dim DirReturn     As String
   Dim dCount        As Integer
   Dim CurrFile      As String
   Dim CurrDir       As String
   Dim dstPathBackup As String
   Dim f             As Integer
   Dim d()           As String
   ReDim d(100) As String
   On Error GoTo DirErr
   CurrDir$ = CurDir$
   ' If Path lacks a "\", add one to the end
   If Right$(srcPath, 1) <> "\" Then srcPath = srcPath & "\"
   srcPath = UCase$(srcPath)
   If Right$(dstPath, 1) <> "\" Then dstPath = dstPath & "\"
   dstPath = UCase$(dstPath)
   dstPathBackup = dstPath
   ' Initialize var to hold filenames
   DirReturn = Dir(srcPath & "*.*", ATTR_DIRECTORY)
   ' Find all subdirs
   Do While DirReturn <> ""
      ' Make sure we don't do anything with "." and "..", they aren't real files
      If DirReturn <> "." And DirReturn <> ".." Then
         If (GetAttr(srcPath & DirReturn) And ATTR_DIRECTORY) = ATTR_DIRECTORY Then
            ' It's a dir. Add it to dirlist
            dCount = dCount + 1
            d(dCount) = srcPath & DirReturn
         End If
      End If
      DirReturn = Dir
   ' Now do all the files matching FilePath (and make sure we don't do the dirs)
   DirReturn = Dir(srcPath & FilePat, 0)
   ' Find all files
   Do While DirReturn <> ""
      ' Make sure we don't get a dir
      If Not ((GetAttr(srcPath & DirReturn) And ATTR_DIRECTORY) = ATTR_DIRECTORY) Then
         ' It's a file. Copy it
         Frm_Copy!Lbl_CopyInfo.Caption = "Copying " & srcPath & DirReturn & " to " & dstPath & DirReturn
         ' Make sure the file doesn't already exist. If it exists, prompt the user
         ' to overwrite it.
         On Error Resume Next
         f = FreeFile
         Open dstPath & DirReturn For Input As #f
         Close #f
         If Err = 0 Then
            ' Prompt the user
            f = MsgBox("The file " & dstPath & DirReturn & " already exists. Do you wish to overwrite it?", 4 + 32 + 256)
            If f = 6 Then FileCopy srcPath & DirReturn, dstPath & DirReturn
            FileCopy srcPath & DirReturn, dstPath & DirReturn
         End If
      End If
      DirReturn = Dir
   ' Now do all subs
   For i = 1 To dCount
      ' Check the 'IncludeSubDirs' value. If it's true, we have to make
      ' a dir called 'd(i)' in dstPath, and then assign dstPath & d(i) as
      ' dstPath
      If IncludeSubDirs Then
         On Error GoTo PathErr
         dstPath = dstPath & Right$(d(i), Len(d(i)) - Len(srcPath))
         ' If the Path exists, then this will work out, if not, an error
         ' will be generated and trapped, and the dir will be made
         ChDir dstPath
         On Error GoTo DirErr
         ' Since we aren't recoursing, we're done
         CopyFiles = True
         GoTo ExitFunc
      End If
      DirOK = CopyFiles(d(i), dstPath, IncludeSubDirs, FilePat, Frm_Copy)
      ' Reset dstPath to the value assigned at the argument-line
      dstPath = dstPathBackup
   CopyFiles = True
   ChDir CurrDir$
   Exit Function
   Frm_Copy!Lbl_CopyInfo = "Error: " & Error$(Err)
   CopyFiles = False
   Resume ExitFunc
   ' Didn't find the Dir'ed path
   If Err = 75 Or Err = 76 Then
      Frm_Copy!Lbl_CopyInfo.Caption = "Making directory " & dstPath
      MkDir dstPath
      Resume Next
   End If
   GoTo DirErr
End Function


From: brockway Date: Thursday, June 24 1999 - 05:51AM CDT  
Thanks everyone. I shall post you all as many points as poss. I've had to email the site managers to figure out how to award multiple experts, so look for them soon.

Thanks again.


From: brockway Date: Thursday, June 24 1999 - 02:08PM CDT  
I am rejecting these responses  (clicking the REJECT box) so that the question can be deleted and the points refunded so that the points can be  awarded among the serveral experts who answered the question. (as per advice fron the administrators of Experts Exchange).

Thanks to all

darinwAuthor Commented:
Customer Service @ Experts Exchange


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.