Avg. Rating 5.0
Tags:



Problem

How can we use ColdFusion to recursively move files from one folder into another?

Solution

ColdFusion's cfdirectory tag allows you to quickly get all the files under a folder. One solution would be to simply list all the files from the source directory and then copy each to the destination. However - you have to ensure that subdirectories exist under the destination directory that matches the source directory.

Detailed explanation

To move, or copy, files from one folder to another, begin by creating a list of files within the source directory. In the code block below I've defined a source and destination directory and created a list of files from the source directory. Note that we filter the list to files and use the recurse option.

<cfset sourcedir = expandPath("./mgtest1")>
<cfset destdir = expandPath("./mgtestdump")>

<cfdirectory action="list" directory="#sourcedir#"
recurse="true" name="files" type="file">

Now we need to loop over the query returned by cfdirectory.

<cfloop query="files">

For each file, we need to determine if the file is in a subdirectory under the source folder.
This can be checked with a simple replace on the directory and file from the query record:

    <!--- get the subdir under source dir if there --->
    <cfset subdir = replace(directory, sourcedir, "")>
    <cfif len(subdir)>

If we have a value for subdir, then it will be a subdirectory we may need to create in the destination:

        <!--- create the dir in dest if not there --->
        <cfif not directoryExists(destdir & "/" &
subdir)>
            <cfdirectory action="create"
directory="#destdir#/#subdir#">
        </cfif>

Finally we wrap the IF block that checked the length of subdir, move (or copy) the file, and close the loop:

    </cfif>
    <cffile action="move" source="#directory#/#name#"
destination="#destdir#/#subdir#/#name#">
</cfloop>

This code specifically doesn't handle empty sub directories in the source directory. The complete code listing may be found below:

<cfset sourcedir = expandPath("./mgtest1")>
<cfset destdir = expandPath("./mgtestdump")>

<cfdirectory action="list" directory="#sourcedir#"
recurse="true" name="files" type="file">

<cfloop query="files">
    <!--- get the subdir under source dir if there --->
    <cfset subdir = replace(directory, sourcedir, "")>
    <cfif len(subdir)>
        <!--- create the dir in dest if not there --->
        <cfif not directoryExists(destdir & "/" &
subdir)>
            <cfdirectory action="create"
directory="#destdir#/#subdir#">
        </cfif>
    </cfif>
    <cffile action="copy" source="#directory#/#name#"
destination="#destdir#/#subdir#/#name#">
</cfloop>

Done.




+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes