Check if folder can be deleted

Viewed 47

I'm working on a script that will delete files & folders after a certain age and will create a log about the action.

For Each oFile In fso.GetFolder(C.Value).Files
    
    If DateDiff("h", GetFileAge(oFile.Path), Now) > DelAfterH Then
        If IsFileWriteable(oFile.Path) Then
            Call LogResults(oFile.Path, "File deleted!")
            Logged = True
            Kill oFile
        Else
            Call LogResults(oFile.Path, "File protected!")
            Logged = True
        End If
        
    End If
    
Next oFile

A possible issue that can appear is when a file is opened at someone and becomes write protected, so the script should just skip it.
I can easily verify this with a function I found:

Function IsFileWriteable(strFile As String) As Boolean

Dim i As Integer
i = FreeFile
On Error Resume Next
Open strFile For Binary Access Write As #i
Close #i
IsFileWriteable = (Err = 0)

End Function 

Folders are a different story however. Whenever someone has a file opened in the folder, the script will just halt with Run-time error '75'.
Also the same function can not be used in this case.

Is there a way to test the folder with a similar method before trying to delete?
Or I'm just stuck with error handling?

1 Answers

You can offload the delete operation to a helper function that returns true if the file/folder was deleted and false if not.

The function itself suspends error reporting, tries to delete the file and returns a boolean based on the error number. If zero, no error raised.

Private Function TryToDelete(ByVal path As String) As Boolean
    On Error Resume Next
    Kill path
    TryToDelete = Err.Number = 0 'if failed, it would be > 0, i.e. 75
End Function

For Each oFile In fso.GetFolder(C.Value).Files
    
    If DateDiff("h", GetFileAge(oFile.Path), Now) > DelAfterH Then
        If TryToDelete(oFile.Path) Then
            Call LogResults(oFile.Path, "Deleted!")
        Else
            Call LogResults(oFile.Path, "Could not delete.")
        End If
        Logged = True
    End if
Next oFile
Related