Link to home
Start Free TrialLog in
Avatar of soft4u
soft4u

asked on

Copy a directory

I want to copy a directory with all its files to another existing directory. Need complete code. Thanks in advance!
Avatar of TheQuestion
TheQuestion

Private Function CopyFiles(ByVal from_dir As String, ByVal _
    to_dir As String) As Long
Dim files_copied As Long
Dim dirs As Collection
Dim fname As String
Dim search_handle As Long
Dim file_data As WIN32_FIND_DATA
Dim i As Integer

    Set dirs = New Collection

    ' Get the first file.
    search_handle = FindFirstFile( _
        from_dir & "*.*", file_data)
    If search_handle <> INVALID_HANDLE_VALUE Then
        ' Get the rest of the files.
        Do
            ' Get the file name.
            fname = file_data.cFileName
            fname = Left$(fname, InStr(fname, Chr$(0)) - 1)

            ' Skip the files "." and "..".
            If fname <> "." And fname <> ".." Then
                files_copied = files_copied + 1

                ' See if the file is a directory.
                If file_data.dwFileAttributes And _
                    DDL_DIRECTORY Then
                    ' This is a directory.
                    ' Make the new directory.
                    MkDir to_dir & fname

                    ' Save the directory name so
                    ' we can search it later.
                    dirs.Add fname
                Else
                    ' This is not a directory.
                    ' Copy the file.
                    FileCopy from_dir & fname, to_dir & _
                        fname
                End If
            End If

            ' Get the next file.
            If FindNextFile(search_handle, file_data) = 0 _
                Then Exit Do
        Loop

        ' Close the file search hanlde.
        FindClose search_handle
    End If

    ' Search subdirectories.
    For i = 1 To dirs.Count
        fname = dirs(i)
        files_copied = files_copied + CopyFiles(from_dir & _
            fname & "\", to_dir & fname & "\")
    Next i

    CopyFiles = files_copied
End Function

your gonna need these
Declare Function FindFirstFile Lib "kernel32.dll" Alias "FindFirstFileA" ( _
       ByVal lpFileName As String, _
       lpFindFileData As WIN32_FIND_DATA) As Long

Declare Function FindNextFile Lib "kernel32.dll" Alias "FindNextFileA" ( _
       ByVal hFindFile As Long, _
       lpFindFileData As WIN32_FIND_DATA) As Long

Declare Function FindClose Lib "kernel32.dll" ( _
       ByVal hFindFile As Long) As Long
ASKER CERTIFIED SOLUTION
Avatar of vinnyd79
vinnyd79

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Try this:

CopyDirectory "d:\project\functions", "d:\temp"

Public Function CopyDirectory(strSourceFolder As String, strDestinationParent As String)
    Dim objFileSystemObject As FileSystemObject
    Set objFileSystemObject = New FileSystemObject
   
    If Not (objFileSystemObject.FolderExists(strSourceFolder)) Then
        Set objFileSystemObject = Nothing
        Exit Function
    End If
   
    If Not (objFileSystemObject.FolderExists(strDestinationParent)) Then
        objFileSystemObject.CreateFolder (strDestinationParent)
    End If
   
    objFileSystemObject.CopyFolder strSourceFolder, strDestinationParent, True
   
    Set objFileSystemObject = Nothing
End Function

Note: Don't add a "\" to the end of the folder names while calling the functions. Also, don't forget to reference "Microsoft Scripting Runtime" from Project -> References from your VB Menu.

cheers,
srimanth.
simply use FileSystemObject:

Private Sub Form_Load()
    copyFolder "C:\temp1", "C:\temp2"
End Sub

Public Sub copyFolder(ByVal currentDir As String, ByVal newDir As String)
    Dim fso As New FileSystemObject
    fso.CopyFolder currentDir, newDir
End Sub

remember to reference Microsoft Scripting Runtime under Tools -> References...

hope that helps!
-PtG
The method i provided copies sub-directories as well.
bah, srimanth! bah I say! :-) I wanted those points!

soft4u, I recommend srimanth's solution as it provides some error-checking whereas mine assumes the directories exist, etc.

Regards,
PtG
>> The method i provided copies sub-directories as well.

you and me both... but the thing is, I've never used FileSystemObject in my life, so I had to test it out... otherwise, maybe I would've posted before you :-) ... but better to accept code from someone who knows more what they're talking about and remembers to put stuff in like "Set objFileSystemObject = Nothing"

this will be my last post here :-)

Regards,
PtG
Same solution and same words!!! telepathy??? he he he... nay.... will recommend points for u next time!!! ;)
Hi soft4u,

I personally would recommend vinnyd79's solution, it doesn't require that Microsoft Internet Explorer is installed or that the scripting engine is available. Neither of these conditions can in fact be guaranteed. FSO is designed for use within VBScript where there is no alternative and not for VB proper. An API solution is in fact the most efficient and this has the benefit of also using the standard windows dialog boxes to inform your user of what is going on (this can be turned off if desired).

Tim Cottee MCSD, MCDBA, CPIM
Brainbench MVP for Visual Basic
http://www.brainbench.com

Experts-Exchange Advisory Board Member
Tim, come on, I don't see the problem with promoting inefficient solutions! I mean, sure, API is faster, more efficient, and automatically will work with Windows while scripting will only work with the proper things installed... :-)

soft4u, don't let Tim bully you around! :-) well, of course API will be the better choice in just about every situation that involves the operating system. But if you want to use just a couple lines of code to do the job and you don't have to worry about a whole bunch of people using very different computers in different environments trying to use your program, M$ Scripting Runtime provides some useful, easy-to-use functions.
If the prog is just for you to use: if you're copying very big files or lots of them, use API; if you're just copying a bunch of small files or a couple somewhat large files, or just a directory structure without too many files, and you don't need to see file progress or anything, go ahead and use FSO.

Regards to all and disregard to none,
PtG
FSO Rules!!! I don't care about API. FSO has been created for easy use and if exists then why not use it!!!

Even if API were efficient, it would marginally beat FSO, coz at the end of the day, FSO also would use the same APIs internally!!!
PAFSO RULES!
vinnyd79 as an honorary member I second that ... Go PAFSO.

PtG: No intention of bullying, FSO has its place, that is VBScript. Indeed as you say if it is a simple task then any method that gets the job done is the right method at the time!

srimanth:  API methods are significantly faster than FSO. Yes indeed it does simply wrap the API methods but that is like saying that if you put a ferrari body on a mini chassis then it would perform like a ferrari. The fact is that it won't. It also as mentioned has the problem that it will not work at all if scripting runtime has been disabled by a system administrator, or if it isn't installed. Given that, for VBScript it is the only solution and works well there for what it is designed to do.