2012/06/26

How to delete all files and folders in a directory

I am a frequent member in several forums and spend at least 2 hours on them everyday. Recently I have seen most friends ask the same question:”How do I delete a directory with all the files and folders in it?” I want to explain how to delete all files and folders in a directory here.


Step 1 Define a folder which you want to delete.
<cfset tDirectory = "C:\myFolder\"> <!--- this can be passed in a varaible or whatever --->

Step 2 Take advantage of Windows ODS command RMDIR.
We need to create a string which we will writeinto a .bat file. .bat file is sued to be executed in Windows later down in this article.

<cfset tString ="RMDIR /S /Q " & tDirectory> <!--- This is what we will put in the bat file --->

What? You do not know RMDIR? Donot worry. Let me explain it to you. RMDIR is a built-in command in Windows operating system, and it is usually used to do what we need by DOS. It will delete a directory as well as all directories, files and folders under the directory. Click “Start” > “Run” > type in cmd > press Enter key. You will enter the Dos window. Then type in rmdir/?. You will get the following attributes:

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\pvarando>rmdir /?

Removes (deletes) a directory.

RMDIR [/S] [/Q] [drive:]path
RD [/S] [/Q] [drive:]path

/S Removes all directories and files in the specified directory
in addition to the directory itself. Used to remove a directory
tree.

/Q Quiet mode, do not ask if ok to remove a directory tree with /S



Step 3 Create the .bat file.
<!--- generate a .BAT file for later execution --->
<cffile action="WRITE" file="#expandPath(".")#\delete.bat" output="#tString#">

Step 4 Execute it with ColdFusion.
<!--- Now execute the file to delete everything (Folder and all sub-folders and files)--->
<cfexecute name="#expandPath(".")#\delete.bat" timeout="60"></cfexecute>

Step 5 To clean things up, let’s delete the .bat file (optional).
<!--- now delete the bat file --->
<cffile action="DELETE" file="#expandPath(".")#\delete.bat">

That’s it.

No comments:

Post a Comment