Jump to content

Delete Folder Contents


hankjrfan
 Share

Recommended Posts

I decided to post this function that I wrote not because I think that it is great or inovative, but because in the support forum a common question is "How do I delete the contents of a folder?"

Func _DirRemoveContents($folder)
    Local $search, $file
    If StringRight($folder, 1) <> "\" Then $folder = $folder & "\"
    If NOT FileExists($folder) Then Return 0
    FileSetAttrib($folder & "*","-RSH")
    FileDelete($folder & "*.*")
    $search = FileFindFirstFile($folder & "*")
    If $search = -1 Then Return 0
    While 1
        $file = FileFindNextFile($search)
        If @error Then ExitLoop
        If StringRight($file, 1) = "." Then ContinueLoop
        DirRemove($folder & $file, 1)
    WEnd
    Return FileClose($search)
EndFunc

That is how I do it. I know you could just just do somthing like DirRemove($folder) then DirCreate($folder), but there are times when this is not a good idea.

Well maybe someone new to autoit will find this useful.

***UPDATED CODE***

With the help of SlimShady.

Edited by hankjrfan
Link to comment
Share on other sites

Hmm, nice code but the same thing can be done with just 1 line of code:

FileDelete("C:/the dir you want to remove the contents from/*")

The wildcard (*) says everthing that can be placed there must be removed, so you can also remove all files with one extension:

FileDelete("C:/the dir you want to delete all txt files from/*.txt")
Edited by svennie
Sorry for my English, I'm Dutch... =DMedia UDFINet Adv UDF
Link to comment
Share on other sites

Hmm, nice code but the same thing can be done with just 1 line of code:

FileDelete("C:/the dir you want to remove the contents from/*")

The wildcard (*) says everthing that can be placed there must be removed, so you can also remove all files with one extension:

FileDelete("C:/the dir you want to delete all txt files from/*.txt")
But FileDelete will not delete subfolders or will it?
Link to comment
Share on other sites

Hmm, there you have a point but when you only want to remove the files this is faster.

Updated.

Func _DirRemoveContents($folder)
    Local $search,$file
    If StringRight($folder,1) <> "\" Then $folder = $folder & "\"
    If Not FileExists($folder) Then Return 0
    FileDelete($folder & '*')
    $search = FileFindFirstFile($folder & "*.*")  
    If $search = -1 Then Return 0
    While 1
        $file = FileFindNextFile($search)
        If @error Then ExitLoop
        If StringRight($file,1) = "." Then ContinueLoop
        If FileGetAttrib($folder & $file) = "D" Then DirRemove($folder & $file, 1)
    WEnd
    FileClose($search)
    Return 1
EndFunc
Link to comment
Share on other sites

Nice, but it carries a problem if the directories have other attributes.

$folder = @HomeDrive & '\test'
If Not FileExists($folder) Then
    DirCreate($folder)
    FileSetAttrib($folder, 'H')
    MsgBox(0, 'Show HD Attribute', FileGetAttrib($folder))
    DirRemove($folder)
EndIf
Link to comment
Share on other sites

Nice, but it carries a problem if the directories have other attributes.

$folder = @HomeDrive & '\test'
If Not FileExists($folder) Then
    DirCreate($folder)
    FileSetAttrib($folder, 'H')
    MsgBox(0, 'Show HD Attribute', FileGetAttrib($folder))
    DirRemove($folder)
EndIf
I knew we forgot something B)

Func _DirRemoveContents($folder)
    Local $search,$file
    If StringRight($folder,1) <> "\" Then $folder = $folder & "\"
    If Not FileExists($folder) Then Return 0
    FileDelete($folder & '*.*') ;// Delete all files
    $search = FileFindFirstFile($folder & "*") ;// Find folders
    If $search = -1 Then Return 0
    While 1
        $file = FileFindNextFile($search)
        If @error Then ExitLoop
        If StringRight($file,1) = "." Then ContinueLoop
        If StringInStr(FileGetAttrib($folder & $file), "D") Then DirRemove($folder & $file, 1)
    WEnd
    Return FileClose($search)
EndFunc
Edited by SlimShady
Link to comment
Share on other sites

I knew we forgot something B)

Func _DirRemoveContents($folder)
    Local $search,$file
    If StringRight($folder,1) <> "\" Then $folder = $folder & "\"
    If Not FileExists($folder) Then Return 0
    FileDelete($folder & '*.*');// Delete all files
    $search = FileFindFirstFile($folder & "*");// Find folders
    If $search = -1 Then Return 0
    While 1
        $file = FileFindNextFile($search)
        If @error Then ExitLoop
        If StringRight($file,1) = "." Then ContinueLoop
        If StringInStr(FileGetAttrib($folder & $file), "D") Then DirRemove($folder & $file, 1)
    WEnd
    Return FileClose($search)
EndFunc
Thanks for your additions SlimShady. I never thought of running FileDelete before starting the loop. That should speed things up quite a bit in some situations and I guess I have never tried to delete the contents of a folder that had a hidden subdirectory. Also could we not just do this:

Func _DirRemoveContents($folder)
    Local $search,$file
    If StringRight($folder,1) <> "\" Then $folder = $folder & "\"
    If Not FileExists($folder) Then Return 0
    FileDelete($folder & '*.*');// Delete all files
    $search = FileFindFirstFile($folder & "*");// Find folders
    If $search = -1 Then Return 0
    While 1
        $file = FileFindNextFile($search)
        If @error Then ExitLoop
        If StringRight($file,1) = "." Then ContinueLoop
        DirRemove($folder & $file, 1)
    WEnd
    Return FileClose($search)
EndFunc

Do we still have to check the attributes? If we have already ran FileDelete then all that should be left are folders right?

Edited by hankjrfan
Link to comment
Share on other sites

Do we still have to check the attributes? If we have already ran FileDelete then all that should be left are folders right?

very true.

updated once again. more error checking.

Func _DirRemoveContents($folder)
    Local $search, $file
    If StringRight($folder, 1) <> "\" Then $folder = $folder & "\"
    If NOT FileExists($folder) Then Return 0
    If NOT FileDelete($folder & '*.*') Then Return 0
    $search = FileFindFirstFile($folder & "*")  ;// Find folders
    If $search = -1 Then Return 0
    While 1
        $file = FileFindNextFile($search)
        If @error Then ExitLoop
        If StringRight($file, 1) = "." Then ContinueLoop
        If NOT DirRemove($folder & $file, 1) Then ExitLoop
    WEnd
    Return FileClose($search)
EndFunc
Edited by SlimShady
Link to comment
Share on other sites

After Some thought I have decided to make some changes.

The following line would return 0 when the files were not found. So this would be a problem if there were subdirectories but no files.

If NOT FileDelete($folder & '*.*') Then Return 0

So i think we should just stick with this:

FileDelete($folder & '*.*')

And this line. It would exit if there were a problem deleteing one subfolder, but I do not think that that is a reason not to continue to try to delete the rest.

If NOT DirRemove($folder & $file, 1) Then ExitLoop

So I think we should just use this.

DirRemove($folder & $file, 1)
Link to comment
Share on other sites

@hankjrfan, thanks for the post. I have an immediate need for this..

If you want to really shorten what you are trying to do. Try using this function I just came across..

FileRecycle

--------------------------------------------------------------------------------

Sends a file or directory to the recycle bin.

Syntax: FileRecycle ( "source" )

Parameters: source The source path of the file(s) or directory to Recycle. Wildcards are supported.

Return Value:

Success: Returns 1.

Failure: Returns 0 (typically meaning the file is in use or does not exist).

Remarks:

See FileFindFirstFile for a discussion of wildcards.

To remove a directory, simply give the path without a trailing backslash.

Related: FileDelete, FileRecycleEmpty

Example: FileRecycle("C:\*.tmp")

Why do it one at a time when you can just dump the whole thing. :o

Cheers.. B)

Edited by busysignal
Link to comment
Share on other sites

  • 1 year later...

I know this is an old post but i have a enhanced that function a bit since the function in this post would stop when errors occur. Mine doesn't..

#Include <File.au3>

_DirRemoveContents(@TempDir)

Func _DirRemoveContents($folder)
    Local $list_of_contents, $status
    $list_of_contents = _FileListToArray($folder)
    If StringRight($folder, 1) <> "\"  Then $folder = $folder & "\" 
    If @error = 1 Then Return 3 ; No Files\Folders Found
    For $a = 1 To $list_of_contents[0]
        FileSetAttrib($folder & "\" & $list_of_contents[$a], "-RSH")
        If StringInStr(FileGetAttrib ($folder & $list_of_contents[$a]), "D") Then
            $status = DirRemove($folder & $list_of_contents[$a], 1)
        Else
            $status = FileDelete($folder & $list_of_contents[$a])
        EndIf
    Next    
EndFunc   ;==>_DirRemoveContents

Cheers

My little company: Evotec (PL version: Evotec)

Link to comment
Share on other sites

@MadBoy

Even this script doesn't work perfect..

try you script on the internet explorer cache folder

get the size of the folder

afterwards

use the followingcode

Runwait(@ComSpec & " /c " & "Del " & '"' & @UserProfileDir & '\Local Settings\Temporary Internet Files\Content.IE5\*.*" /Q/S/F', "", @SW_HIDE)

and see the real result

More files are deleted AutoIT has no real alternative to the Del /Q/S/F command

Best regards,

Emiel

Best regards,Emiel Wieldraaijer

Link to comment
Share on other sites

@MadBoy

Even this script doesn't work perfect..

try you script on the internet explorer cache folder

get the size of the folder

afterwards

use the followingcode

Runwait(@ComSpec & " /c " & "Del " & '"' & @UserProfileDir & '\Local Settings\Temporary Internet Files\Content.IE5\*.*" /Q/S/F', "", @SW_HIDE)

and see the real result

More files are deleted AutoIT has no real alternative to the Del /Q/S/F command

Best regards,

Emiel

Try this one then? I've added removal of -A attribute and as you notice all the files in Content.IE5 have that attribute. Should work <_<

#Include <File.au3>

_DirRemoveContents(@UserProfileDir & '\Local Settings\Temporary Internet Files\Content.IE5')

Func _DirRemoveContents($folder)
    Local $list_of_contents, $status
    $list_of_contents = _FileListToArray($folder)
    If IsArray($list_of_contents) Then
        If StringRight($folder, 1) <> "\"  Then $folder = $folder & "\" 
        If @error = 1 Then Return 1 ; No Files\Folders Found
        For $a = 1 To $list_of_contents[0]
            FileSetAttrib($folder & "\" & $list_of_contents[$a], "-RASH")
            If StringInStr(FileGetAttrib($folder & $list_of_contents[$a]), "D") Then
                $status = DirRemove($folder & $list_of_contents[$a], 1)
            Else
                $status = FileDelete($folder & $list_of_contents[$a])
            EndIf
        Next
    Else
        Return 2 ; Directory doesn't exists
    EndIf
EndFunc   ;==>_DirRemoveContents
Edited by MadBoy

My little company: Evotec (PL version: Evotec)

Link to comment
Share on other sites

  • 9 years later...
On ‎22‎.‎10‎.‎2007 at 11:49 AM, MadBoy said:

 

Try this one then? I've added removal of -A attribute and as you notice all the files in Content.IE5 have that attribute. Should work <_<

 

 

#Include <File.au3>

_DirRemoveContents(@UserProfileDir & '\Local Settings\Temporary Internet Files\Content.IE5')

Func _DirRemoveContents($folder)
    Local $list_of_contents, $status
    $list_of_contents = _FileListToArray($folder)
    If IsArray($list_of_contents) Then
        If StringRight($folder, 1) <> "\"  Then $folder = $folder & "\" 
        If @error = 1 Then Return 1 ; No Files\Folders Found
        For $a = 1 To $list_of_contents[0]
            FileSetAttrib($folder & "\" & $list_of_contents[$a], "-RASH")
            If StringInStr(FileGetAttrib($folder & $list_of_contents[$a]), "D") Then
                $status = DirRemove($folder & $list_of_contents[$a], 1)
            Else
                $status = FileDelete($folder & $list_of_contents[$a])
            EndIf
        Next
    Else
        Return 2 ; Directory doesn't exists
    EndIf
EndFunc   ;==>_DirRemoveContents

you have an extra & "\"

in

Quote

FileSetAttrib($folder & "\" & $list_of_contents[$a], "-RASH")

thank you

is working with all cached files

c

Edited by oneLess
Link to comment
Share on other sites

Here is a working function and example of how to delete the content of a folder in Windows. This will delete everything inside the specified folder without deleting the folder itself. 

The only files that could remain are files that are already in used and thus cannot be deleted by Windows.

$location = "C:\Windows\Temp\"

deletefolder($location)

func deletefolder ($path)

RunWait(@ComSpec & " /c " & 'del /s /f /q "' & $path & "*.*" & '"', "", @SW_HIDE) ;delete all files in the directory and sub directories

RunWait(@ComSpec & " /c " & 'del /s /f /q "' & $path & "*.*" & '" /A:H', "", @SW_HIDE) ;delete all hidden files in the directory and sub directories

RunWait(@ComSpec & " /c " & 'for /f "delims=?" %f in (''dir /ad /b ' & '"' & $path & '"' & ''') do rd /s /q "' & $path & '%f"', "", @SW_HIDE) ;list all subfolders and delete them

EndFunc

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...