Get A Folder Size Using ColdFusion and FSO...

This tutorial will demonstrate how you can get the size of space used in a directory (and all sub directories/files) in your account. This is useful if you want to see how much space you are using in your hosting account.

The first thing you must keep in mind is that the FileSystemObject must be in place for this work, most "WINDOWS" based hosting companies have this enabled, but if in doubt.. please contact your hosting provider.

The first thing you must do is to specify the directory that we will be checking to, this is usually the root of your account.
<!--- Define the path to check usage on --->
<cfset Folder2Check = "C:\inetpub\wwwroot\">

The next thing we do is connect to the FyleSystemObject object on the Windows Server. The code below first tries to connect to it via the CFOBJECT tag. If ColdFusion isn't able to connect to it, it then creates an instance so that it CAN connect.
<!--- Connect to the File System Object --->
<cflock timeout="30" throwontimeout="No" name="#CreateUUID()#" type="EXCLUSIVE">
    <cftry>
        <cfobject type=
"COM" 
                      name=
"FSO" 
                      class=
"Scripting.FileSystemObject" 
                      action=
"CONNECT">
          </cfobject>
        <cfcatch>
            <cfobject type=
"COM" 
                          name=
"FSO" 
                          class=
"Scripting.FileSystemObject" 
                          action=
"CREATE">
            </cfobject>
        </cfcatch> 
    </cftry> 
</cflock>

The next thing we will do is to use CFSCRIPT to connect to the object's session on the server and get the folder size. If this fails it will return a size of "0".
<cftry>
    <cfscript>
       
objFolder      = FSO.getFolder(
Folder2Check);
        objFolderSize = LSParseNumber(objFolder.size); 
    </cfscript> 
    <cfcatch>
        <cfset objFolderSize =
0>
    </cfcatch>
</cftry>

The last thing we need to do is to actually display the total usage value:
<cfoutput>
   
Total Space Used: #LSParseNumber(DecimalFormat(Evaluate(objFolderSize / 1000000)))#
</cfoutput>

That's it, you can now find out how much space is being used in a folder (and sub folders..)

Questions? Comments? Email me...



All ColdFusion Tutorials By Author: Pablo Varando