Using ColdFusion to Count the Files in a Directory

<CFDIRECTORY> Add comments

I’m frequently building dashboard tools, and this is a handy and simple trick.  It basically uses CFDIRECTORY to build a query, and then queries the query for Type = ‘File’.  I just ask for a COUNT in the second QUERY, since I’m not really interested in the other data and like to keep things fast.

Here’s the code as a handy function that you can drop into a component.

<cffunction name="fileCount" returnType="numeric" output="false">

<cfargument 	name="folderLoc" 		required="no">
<cfparam 			name="folderLoc" 		default="">

<cfdirectory directory="#folderLoc#" action="list" recurse="true" name="getAllFolders">

<cfquery 
	name			="examineThis" 
	dbtype		="query"
	>
  SELECT    COUNT(*) AS NumberOfFiles
  FROM    	getAllFolders
  WHERE    	Type = 'File'
</cfquery>

<cfreturn #val(examineThis.NumberOfFiles)#>

</cffunction>

3 responses to “Using ColdFusion to Count the Files in a Directory”

  1. Ed Sullivan Says:
    Great post. Would love to see some of your stuff in the ColdFusion Cookbook: http://cookbooks.adobe.com/coldfusion. Thanks! Ed Sullivan esulliva@adobe.com
  2. Michael Cummins Says:
    Thanks! I really appreciate it!
  3. Devin Says:
    There's no need for a second query in this case. In the cfdirectory tag, you can specify: type="file", which only returns the files. Then you can refer to the "recordCount" property on the result.

Leave a Reply

Leave this field empty:

Powered by Mango Blog. Initial Template Design and Icons by N.Design Studio, modified by Michael Cummins.