RobotStudio event

RAPID:Removing a directory with contents

SpencerXZ
SpencerXZ
edited June 2016 in RobotStudio
Hello, 

I'm needing a way to delete my backups folder. I have way too many robots to walk around deleting backups every month, I want to clear out the folder on a schedule. I already know how I want to do the schedule, I just can't figure out how to delete the files since RemoveDir only works on empty directories. I tried using a while loop and IsFile but I ran into the problem of not knowing how many subdirectories there will be. Here's how the controller files are stored:

hd0a/BACKUP/*All Backups are Here*

Some robots contain only 1-5 backups in the Backup folder, but some have 10+ 

I need a way to delete all of these with Rapid Code. Thank you!

Here is what I have so far. Deleting files is easy. Deleting an unknown amount of subdirectories with contents is hard:



Post edited by SpencerXZ on

Comments

  • John_Verheij
    John_Verheij ✭✭✭
    edited June 2016
    Hi,

    You can recursively delete all the files in a sub-directory and then delete the sub-directory. Some remarks
    - You are not using the "IsFile" function correctly. According to the manual: "When no type is specified, it returns TRUE if the file exists and otherwise FALSE. So this is not the correct way to distinguish between a file and directory. 
    - Furthermore the functions support full or relative paths. Relative often means with respect to current working directory. So in theory it will work correctly, but with my virtual controller it was sometimes looking in "C:/" and not in the correct path...

    Here an example how you can implement it...

        PROC RemoveDirWithContent(string Path)
            VAR dir Dev;
            VAR string FileName;
            
            ! Open directory
            OpenDir Dev, Path;
            
            ! Get contents of directory
            WHILE ReadDir(Dev, FileName) DO
                
                ! Check if is file
                IF IsFile(FileName \Directory) THEN
                   
                    IF FileName <> "." AND FileName <> ".." THEN
                    
                        ! Recursively delete content in sub-dir
                        RemoveDirWithContent(Path+"/"+FileName);
                    
                        ! Remove sub-dir
                        RemoveDir(Path+"/"+FileName);
                    
                    ENDIF
                ELSE               
                    
                    ! Remove File
                    RemoveFile(Path+"/"+FileName);
                ENDIF
            ENDWHILE
            
            ! Close Dir
            CloseDir Dev;
            
            ERROR
                TRYNEXT;
        ENDPROC
        
        PROC Main()
            RemoveDirWithContent("HOME:/Test");
        ENDPROC