Using <cfdirectory>

Contact Us or call 1-877-932-8228
Using <cfdirectory>

Using <cfdirectory>

The <cfdirectory> tag is used for working with directories. The action attribute of <cfdirectory> dictates what action will be performed on the directory in question. The table below describes the different actions that can be performed.

<cfdirectory> Actions
Action Description
list Reads the contents of a directory on the server into a query object.
create Creates a new directory on the server.
move Moves a directory on the server from one location to another.
rename Renames (or moves) a directory on the server.

Listing Directory Contents

The following demo shows how to list the contents in a directory with <cfdirectory>.

Code Sample:

FilesAndDirs/Demos/RunningLogList.cfm
<html>
<head>
<title>Running Logs</title>
</head>
<body>
<h1>Running Logs</h1>
<cfdirectory action="list" directory="#ExpandPath('Logs')#" name="loglist">

<table border="1">
<tr>
	<th>File Name</th>
	<th>File Size</th>
	<th>File or Directory</th>
	<th>Date Last Modified</th>
</tr>
	<cfoutput query="loglist">
	<tr>
		<td><a href="RunningLog-2.cfm?log=#name#">#name#</a></td>
		<td>#size#</td>
		<td>#type#</td>
		<td>#DateLastModified#</td>
	</tr>
	</cfoutput>
</table>
</body>
</html>

Things to note about this code:

  • The ExpandPath() function is used in the directory attribute of the <cfdirectory> tag to find the absolute path to the logs file.
  • <cfdirectory> returns the directory list as a query object just as a query to a database would. The <cfoutput> tag is used with the query attribute set to the name specified in <cfdirectory> to loop through the directory contents.
  • Columns of the result set returned by <cfdirectory> include Name, Size, Type, DateLastModified.
  • The file name is linked to RunningLog-2.cfm with the file name sent on the query string.

RunningLog-2.cfm is the same as RunningLog.cfm except that the file it reads is determined from the value passed in the query string. The code follows.

Code Sample:

FilesAndDirs/Demos/RunningLog-2.cfm
               <cfparam name="URL.log" default="RunningLog.txt">
<html>
<head>
  <title>Running Log</title>
</head>
<body>
<h1>Running Log</h1>
<a href="AddEntry.cfm">Add Entry</a><hr/>
<cfset RunningLogPath = ExpandPath("Logs/#URL.log#")>
<cfset CrLf = chr(10) & chr(13)>
<cfif FileExists(RunningLogPath)>
	<cffile action="read" file="#RunningLogPath#" variable="myfile">
	<cfloop list="#myfile#" index="run" delimiters="#CrLf#">
		<cfoutput>#run#<br></cfoutput>
	</cfloop>
<cfelse>
	You have apparently never been running.
</cfif>

</body>
</html>
Next