Adobe ColdFusion 8

Example 1: Using the FileSystem object

The following example uses the Microsoft FileSystem Scripting object in the Application scope. This code creates a user-defined function that returns a structure that consists of the drive letters and free disk space for all hard drives on the system.

<cfapplication name="comtest" clientmanagement="No" Sessionmanagement="yes">

<!--- Uncomment the following line if you must delete the object from the
Application scope during debugging. Then restore the comments. 
This technique is faster than stopping and starting the ColdFusion server. --->
 <!--- <cfset structdelete(Application, "fso")> --->

<!--- The getFixedDriveSpace user-defined function returns a structure with
the drive letters as keys and the drive's free space as data for all fixed 
drives on a system. The function does not take any arguments --->

<cffunction name="getFixedDriveSpace" returnType="struct" output=True>
    <!--- If the FileSystemObject does not exist in the Application scope,
    create it. --->
    <!--- For information on the use of initialization variables and locking in
        this code, see "Locking application variables efficiently" in Chapter 15,
        "Using Persistent Data and Locking" --->
    <cfset fso_is_initialized = False>
    <cflock scope="application" type="readonly" timeout="120">
        <cfset fso_is_initialized = StructKeyExists(Application, "fso")>
    </cflock>
    <cfif not fso_is_initialized >
        <cflock scope="Application" type="EXCLUSIVE" timeout="120">
            <cfif NOT StructKeyExists(Application, "fso")>
                <cfobject type="COM" action="create" class="Scripting.FileSystemObject"
                    name="Application.fso" server="\\localhost">
            </cfif>
        </cflock>
    </cfif>

    <!--- Get the drives collection and loop through it to populate the
        structure. --->
    <cfset drives=Application.fso.drives()>
    <cfset driveSpace=StructNew()>
    <cfloop collection="#drives#" item="curDrive">
        <!--- A DriveType of 2 indicates a fixed disk --->
        <cfif curDrive.DriveType IS 2>
        <!--- Use dynamic array notation with the drive letter for the struct key
        --->
            <cfset driveSpace["#curDrive.DriveLetter#"]=curDrive.availablespace>
        </cfif>
    </cfloop>
    <cfreturn driveSpace>
</cffunction>

<!--- Test the function. Get the execution time for running the function --->
<cfset start = getTickCount()>
<cfset DriveInfo=getFixedDriveSpace()>
<h3>Getting fixed drive available space</h3>
<cfoutput>Execution Time: #int(getTickCount()-start)# milliseconds</cfoutput><br><br>
<cfdump label="Drive Free Space" var="#driveInfo#">