Search code examples
directoryautoit

How to delete all files in a directory?


My script :

#RequireAdmin
FileDelete("C:\Users\Administrator\Desktop\temp\")

I want to delete all files in that directory. I also tried :

#RequireAdmin
DirRemove("C:\Users\Administrator\Desktop\temp\")

But it's not working, any suggestion?


Solution

  • The syntax for FileDelete() is FileDelete("filename") ;not only directory!. You can also use wildcards for filename (* and ?).

    DirRemove() works as follows: DirRemove ( "path" [, recurse = 0] ). With recurse=0 (default), deletes the folder, but only if it is empty. With recurse=1 removes files and subdirectories (like the DOS DelTree command).

    Maybe you misunderstood the flag to use:

    ; Remove only the empty folder "Folder_path"
    DirRemove("Folder_Path")
    
    ; Remove folder "Folder_Path" with all subfolder and all files within
    DirRemove("Folder_Path", 1)
    

    If this doesn't work it's a matter of system rights. If you want to delete files without deleting containing folder:

    #include <Files.au3>
    
    ; Get all files in folder and delete them:
    Local $aFilesInRoot = _FileListToArray("Your_Path", 1, True) ; 1=$FLTA_FILES = Return files only,  True=returns full path
    For $i = 1 To $aFilesInRoot[0]
        FileDelete($aFilesInRoot[1])
    Next
    
    ; Get all subfolders under root and delete them:
    Local $aFolderInRoot = _FileListToArray("Your_Path", 2, True) ;2=$FLTA_FOLDERS = Return Folders only
    For $i = 1 To $aFolderInRoot[0]
        DirRemove($aFolderInRoot[1], 1)
    Next
    

    But isn't it easier to remake the deleted folder after deleting all with only one command?