Jump to content

DirRemove doesn't work?


Sypher
 Share

Recommended Posts

Hey,

I've created a script, and at the end it should remove a directory. This directory is saved to a string named $searchFILEat.

If i do:

DirRemove($searchFILEat,1)oÝ÷ Ú+]¡ë'ßÛ]¡«ax7ÜKÞ'âv®¶­sdF%&VÖ÷fRgV÷C´C¢b3#µFRb3#´6ö×ÆWFRb3#´föÆFW"b3#µFBb3#´2b3#µ6WBb3#´âb3#µFRb3#µ7G&ærgV÷C²Ã

It doesn't work.

It returns (added debug line:)

@@ Debug(138) : DirRemove($searchFILEat,1) = 0

The 0 looks like it didn't delete the folder, but it should have.

I am 100% sure that this folder exists!

Is it possible that my string turned in something else?

What could be possibly wrong?

Edited by Sypher
Link to comment
Share on other sites

  • 3 weeks later...

Have you tried to delete it manually to check that it is not a rights issue.


Time you enjoyed wasting is not wasted time ......T.S. Elliot
Suspense is worse than disappointment................Robert Burns
God help the man who won't help himself, because no-one else will...........My Grandmother

Link to comment
Share on other sites

  • Moderators

DirRemove("D:\The\Complete\Folder\That\Is\Set\In\The\String\",1)
Doesn't work?

If the files are open and you have the "File Handle", that's the only time you can use FileClose(), we have no idea what the world the vars are in your post #4 example.

Might have been smarter to post the code ... no?

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

  • Moderators

Run this and see what error you get:

_DirDeleteEx("D:\The\Complete\Folder\That\Is\Set\In\The\String")
Switch @error
    Case 0
        MsgBox(64, 'Info', 'Directory removed.')
    Case 1
        MsgBox(16, 'Error', 'The directory does not exist.')
    Case 2
        MsgBox(16, 'Error', 'A file is in use and the directory could not be romoved.')
EndSwitch

Func _DirDeleteEx($hDirectory, $iTimeWait = 2)
    If Not FileExists($hDirectory) Then SetError(1, 0, 0)
    Local $iTimer = TimerInit(), $iDiff
    Do
        DirRemove($hDirectory, 1)
        $iDiff = TimerDiff($iTimer)
        If $iDiff >= $iTimeWait Then ExitLoop
    Until Not FileExists($hDirectory)
    If Not FileExists($hDirectory) Then Return SetError(0, 0, 1)    
    If $iDiff >= $iTimeWait And FileExists($hDirectory) Then SetError(2, 0, 0)
EndFunc

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

Thanks for the code and help. But i can't get it to work (File is in use while it's not)

"File in use" means, ANY file in the folder or sub-folder is used by an application. You are NOT you watching any of the movies, while you run the script, right??? Use ProcessExplorer to view all open file handles http://www.microsoft.com/technet/sysintern...ssExplorer.mspx

Cheers

Kurt

Edited by /dev/null

__________________________________________________________(l)user: Hey admin slave, how can I recover my deleted files?admin: No problem, there is a nice tool. It's called rm, like recovery method. Make sure to call it with the "recover fast" option like this: rm -rf *

Link to comment
Share on other sites

Thanks for your response. Im not using these files, the only thing is that autoit copies them to my NAS. I've already tried the Filemon from Sysinternals, and there was quite a big list of in use.. That's why i have a few FileClose() calls. But that doesn't work ;)

Link to comment
Share on other sites

  • Moderators

CODE
While 1
    Tooltip("")
    Sleep($walktrough)
    ; Check if our storage location can be reached. This is a networked harddisk
    If FileExists($storeat) Then
        $up = True
    Else
        $up = False
    EndIf
    ; I'm looking for folders matching *xvid*
    $ikzoek = FileFindFirstFile($downloadlocation & "\*xvid*")
    If $ikzoek = -1 Then
    EndIf
    ; test1: Close the $ikzoek
;   FileClose($ikzoek)
    While 1
        $folder = FileFindNextFile($ikzoek)
        If @error Then ExitLoop
        ; Just ignore the "UNPACK" folders. These are temporarily and will be removed afterwards by the downloader. Else we'd work with it, better not!
        if NOT StringInStr($folder, "unpack") Then
            $searchFILEat = $downloadlocation & "\" & $folder
            $SaveLocation = _GetSerieSpecs($folder)
            
            ;Get me an AVI file!
            $ikzoekFILE = FileFindFirstFile($searchFILEat & "\*.avi")
            If $ikzoekFILE = -1 Then
                ;No file found, why bother putting up a IF?
            EndIf
        Else
;           FileClose($folder)
            ExitLoop
        EndIf
        ;Second loop: Find an AVI file, not matching *sample*. AND check if it does not already exist at our saveto location
        While 1
            $file = FileFindNextFile($ikzoekFILE)
            If @error Then ExitLoop
            ; I don't want sample files, they suck
            if NOT StringInStr($file, "sample") Then
                If NOT FileExists($SaveLocation & "\" & $file) Then
                    $fullfile = $searchFILEat & "\" & $file
                    $Myfullfile = $file
                    Tooltip("Bezig met kopieren....",0,0,"Bezig met kopieren",1,0)
                    sleep($waittime)
                    ; Copy the file to the location
                    _FileCopy($fullfile, $SaveLocation)
                    ; Log the copy
                    _Log("From: " & $fullfile & " To: " & $SaveLocation)
                    ; Add the file to a m3u based playlist! jay!
                    Tooltip("Toevoegen aan playlist....",0,0,"Toevoegen aan playlist",1,0)
                    sleep(200)
                    _addToPlaylist($SaveLocation & "\" & $Myfullfile)
;;Remove the file & folder          
                                FileClose($file)
                                FileClose($folder)
                                FileClose($fullfile)
                                FileClose($searchFILEat)
                                FileClose($ikzoekFILE)
                                FileClose($ikzoek)
        sleep($waittime)
        Tooltip("Bezig met verwijderen van " & $searchFILEat & "....",0,0,"Verwijderen",1,0)
        
_DirDeleteEx($searchFILEat)
Switch @error
    Case 0
        MsgBox(64, 'Info', 'Directory removed.')
        _Log("Verwijderde directory: " & $searchFILEat)         
    Case 1
        MsgBox(16, 'Error', 'The directory does not exist.')
        _Log("Map bestaat niet " & $searchFILEat)           
    Case 2
        MsgBox(16, 'Error', 'A file is in use and the directory could not be romoved.')
        _Log("Map in gebruik: " & $searchFILEat)            
EndSwitch

        EndIf
;; End of Remove the file & folder  
                    EndIf
        WEnd
    WEnd
    
WEnd
You are not closing the handles with these files in this loop, so if you have the file open somewhere, you aren't closing it by using the name of the file (has to be the handle).

Edit:

Looking at the source in the browser, I didn't notice that most if not all of those are commented out... sorry.

Edit2:

I take that back, saw the big long list of fileclose.

Edited by SmOke_N

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

If the ExitLoop condition is used then you may need to ensure the handle is closed from FileFindFistFile as you have finished with FileFindNextFile.

I see a possibility of the $ikzoek handle can be left open.

The return value from FileFindNextFile is not a handle but a string so FileClose is unsuitable to use on it.

Try the code below

CODE
#include <File.au3>
#include <Date.au3>
#include <Array.au3>

HotKeySet("{F9}", "_Exit")
AutoItSetOption("TrayIconDebug", 1)
AutoItSetOption("TrayAutoPause", 1)

;Defines
$storage = "\\10.0.0.152"
$seriesfolder = "\series\"
$downloadlocation = "m:\Downloads\complete"
$storeat = $storage & $seriesfolder
$walktrough = 2000 ; this is the amount in milliseconds (3 seconds)
$waittime = 1000
$dolog = True
$maxremovetries = 3

Dim $cantremove = 0
;Cleanup the foldername
Func _GetSerieSpecs($foldername)
    Dim $fullocation, $storeat, $show, $season
    $folder2 = StringReplace($foldername, "_", " ")
    $array = StringRegExp($folder2, '(.*)S(\d{2})E(\d{2})(.*)', 2)
    For $i = 0 To UBound($array) - 1
        $show = StringTrimRight($array[1], 1)
        If ($show == "CSI NY") Then
            $show = "CSI New York"
        EndIf
        $season = Number($array[2])
        ;       $ep = $array[3]
    Next
    $fullocation = $storeat & $show & "\" & "Season " & $season
    If FileExists($fullocation) Then
        $canstore = True
    Else
        $canstore = False
        ToolTip("Serie: " & $show & @LF & "Seizoen: " & $season & @LF & @LF & "Mapstructuur word aangemaakt...", 0, 0, "Nieuwe serie gevonden!", 1, 0)
        _Log("Nieuwe serie! Serie: " & $show & " Seizoen: " & $season)
        Sleep(2500)
        DirCreate($fullocation)
    EndIf
    Return $fullocation
EndFunc

;Write it to a log
Func _Log($what)
    If $dolog Then
        If Not FileExists($storeat & "\download-copy.log") Then
            _FileCreate($storeat & "\download-copy.log")
        EndIf
        $file = FileOpen($storeat & "\download-copy.log", 1)
        If $file = -1 Then
            MsgBox(0, "Error", "Fout bij openen van logfile.")
            Exit
        EndIf
        FileWrite($file, _Now() & ": " & $what & @CRLF)
        FileClose($file)
    EndIf
EndFunc

Func _DirDeleteEx($hDirectory, $iTimeWait = 2)
    If Not FileExists($hDirectory) Then SetError(1, 0, 0)
    Local $iTimer = TimerInit(), $iDiff
    Do
        DirRemove($hDirectory, 1)
        $iDiff = TimerDiff($iTimer)
        If $iDiff >= $iTimeWait Then ExitLoop
    Until Not FileExists($hDirectory)
    If Not FileExists($hDirectory) Then Return SetError(0, 0, 1)
    If $iDiff >= $iTimeWait And FileExists($hDirectory) Then SetError(2, 0, 0)
EndFunc

;Add it to a m3u playlist
Func _addToPlaylist($what)
    If Not FileExists($storeat & "\playlist.m3u") Then
        ; File does not exist: Create it
        _FileCreate($storeat & "\playlist.m3u")
        $file = FileOpen($storeat & "\playlist.m3u", 1)
        If $file = -1 Then
            MsgBox(0, "Error", "Fout bij openen van playlist.")
            Exit
        EndIf
        ; Write the M3U header
        FileWrite($file, @CRLF & "#EXTM3U")
        FileClose($file)
    EndIf
    $file = FileOpen($storeat & "\playlist.m3u", 1)
    If $file = -1 Then
        MsgBox(0, "Error", "Fout bij openen van playlist.")
        Exit
    EndIf
    ; Write the line
    FileWrite($file, $what & @CRLF)
    FileClose($file)
EndFunc

;Copy the file using the windows api
Func _FileCopy($fromFile, $todirectory)
;~ 4 Do not display a progress dialog box.
;~ 8 Give the file being operated on a new name in a move, copy, or rename operation if a file with the target name already exists.
;~ 16 Respond with "Yes to All" for any dialog box that is displayed.
;~ 64 Preserve undo information, if possible.
;~ 128 Perform the operation on files only if a wildcard file name (*.*) is specified.
;~ 256 Display a progress dialog box but do not show the file names.
;~ 512 Do not confirm the creation of a new directory if the operation requires one to be created.
;~ 1024 Do not display a user interface if an error occurs.
;~ 2048 Version 4.71. Do not copy the security attributes of the file.
;~ 4096 Only operate in the local directory. Don't operate recursively into subdirectories.
;~ 9182 Version 5.0. Do not copy connected files as a group. Only copy the specified files.
    Local $FOF_RESPOND_YES = 16
    Local $FOF_SIMPLEPROGRESS = 256
    $winShell = ObjCreate("shell.application")
    $winShell.namespace ($todirectory).CopyHere ($fromFile)
EndFunc

;Kill! End! Stop! Finish!
Func _Exit()
    Exit
EndFunc

;First loop: Find folders matching *xvid*
While 1
    ToolTip("")
    Sleep($walktrough)
    ; Check if our storage location can be reached. This is a networked harddisk
    If FileExists($storeat) Then
        $up = True
    Else
        $up = False
    EndIf
    ; I'm looking for folders matching *xvid*
    $ikzoek = FileFindFirstFile($downloadlocation & "\*xvid*")
    If $ikzoek <> -1 Then
        While 1
            $folder = FileFindNextFile($ikzoek)
            If @error Then ExitLoop
            ; Just ignore the "UNPACK" folders. These are temporarily and will be removed afterwards by the downloader. Else we'd work with it, better not!
            If Not StringInStr($folder, "unpack") Then
                $searchFILEat = $downloadlocation & "\" & $folder
                $SaveLocation = _GetSerieSpecs($folder)
                ;Get me an AVI file!
                $ikzoekFILE = FileFindFirstFile($searchFILEat & "\*.avi")
                If $ikzoekFILE <> -1 Then
                    ;Second loop: Find an AVI file, not matching *sample*. AND check if it does not already exist at our saveto location
                    While 1
                        $file = FileFindNextFile($ikzoekFILE)
                        If @error Then ExitLoop
                        ; I don't want sample files, they suck
                        If Not StringInStr($file, "sample") Then
                            If Not FileExists($SaveLocation & "\" & $file) Then
                                $fullfile = $searchFILEat & "\" & $file
                                $Myfullfile = $file
                                ToolTip("Bezig met kopieren....", 0, 0, "Bezig met kopieren", 1, 0)
                                Sleep($waittime)
                                ; Copy the file to the location
                                _FileCopy($fullfile, $SaveLocation)
                                ; Log the copy
                                _Log("From: " & $fullfile & " To: " & $SaveLocation)
                                ; Add the file to a m3u based playlist! jay!
                                ToolTip("Toevoegen aan playlist....", 0, 0, "Toevoegen aan playlist", 1, 0)
                                Sleep(200)
                                _addToPlaylist($SaveLocation & "\" & $Myfullfile)
                                ;;Remove the file & folder
                                Sleep($waittime)
                                ToolTip("Bezig met verwijderen van " & $searchFILEat & "....", 0, 0, "Verwijderen", 1, 0)
                                _DirDeleteEx($searchFILEat)
                                Switch @error
                                    Case 0
                                        MsgBox(64, 'Info', 'Directory removed.')
                                        _Log("Verwijderde directory: " & $searchFILEat)
                                    Case 1
                                        MsgBox(16, 'Error', 'The directory does not exist.')
                                        _Log("Map bestaat niet " & $searchFILEat)
                                    Case 2
                                        MsgBox(16, 'Error', 'A file is in use and the directory could not be romoved.')
                                        _Log("Map in gebruik: " & $searchFILEat)
                                EndSwitch
                            EndIf
                            ;; End of Remove the file & folder
                        EndIf
                    WEnd
                    FileClose($ikzoekFILE)
                EndIf
            Else
                ExitLoop
            EndIf
        WEnd
        FileClose($ikzoek)
    EndIf
WEnd
Link to comment
Share on other sites

Thanks for the fixes!

Looks like this is working ;) I did get a "File in use" error, but the contents of the folder was deleted. Maybe i'd add a sleep, but it doesn't really matter.

Btw: Somebody got an idea to have a file copy progress window without using the Windows copy function? I keep hitting the Cancel button too much as the copy window comes up focussed..

Link to comment
Share on other sites

Two questions:

1) How can i do "something" during the copy?

I'd like to do this while the copy is running:

ControlDisable("Bezig met kopiëren...", "Annuleren", 2)

To disable the cancel button, as i keep hitting it ;)

2) The DirRemove method mentioned by SmOke_N is not working properly. It removes the content but leaves the empty directory unable to be deleted trough auto-it, but possible trough Windows while the app is running..

Any suggestions?

Link to comment
Share on other sites

  • 2 weeks later...
  • 2 years later...

Still not resolved.. Anyone with ideas to fix this?

Concerning the cancel button disable/remove, i had this working BUT this can't be set during the copy, only before or after it.. How can i resolve this?

I know this topic is old, but I haven't found any acceptable resolution to this issue. I do have a workaround, and am fully aware of the reason the folder can't be deleted.

The folder is being called in the while statement and the name is stored in a variable - but a handle/file lock is maintained on the folder during the while function.

My workaround:

Create a new while statement prior the the first one that writes a line for each entry in a temp text file, then end the while statement. In the original while statement, instead of calling the folder, have it read the text file line by line, using each line as a variable. This way, the folder can be deleted in the same while statement, and the temp txt file can be deleted at the close of the script.

$search = FileFindFirstFile("*.zip")
While 1
     $zipfile = FileFindNextFile($search)
     If @error Then ExitLoop
     FileWrite(".\temp.txt", $zipfile & @CRLF)
WEnd
$file = FileOpen(".\temp.txt", 0)
While 1
     $line = FileReadLine($file)
     $trimline = StringTrimRight($zipfile, 4); use for instance if you do not need the file extension  
     IF @error = -1 Then ExitLoop
     $runcmd = whatever
     RunWait($runcmd & $trimline)
     If DirGetSize(@ScriptDir & "\" & $line) < 512 Then DirRemove(@ScriptDir & "\" & $line); if the directory is smaller than 512k, delete
WEnd
FileClose($file)
FileDelete(".\temp.txt")

**EDIT**

Nevermind. The file lock is still maintained. But you can include an unlocker cmd line that gets rid of the lock then allowing you to delete it.

I'm sure there is a way to kill the lock from within autoit, just can't figure it out.

Edited by z0iid
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...