Jkrules
Jkrules

Reputation: 21

How to catch exception when attempting to delete a file in use?

I't making a program to delete the files in my temp folder. I've gotten as far as the code to delete the files, But I can't seem to figure out how to skip the files in use or catch the exception so that my program doesn't crash when it attempts to delete a file in use.

Here is the code I have so far:

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        If CheckBox1.Checked = True Then
            Dim s As String
            For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
                System.IO.File.Delete(s)
            Next s
        End If
end sub

Upvotes: 2

Views: 3142

Answers (2)

Steven Doggart
Steven Doggart

Reputation: 43743

When an exception is thrown, once it is handled by the Catch, execution will jump to the End Try. Therefore, where you place the beginning and ending of your Try/Catch block is important. For instance:

Try
    Dim s As String
    For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
        System.IO.File.Delete(s)
    Next s
Catch ex As IOException
End Try

In the above example, if any call to Delete fails, it will jump to the End Try and skip the rest of the iterations of the For loop (thereby skipping the rest of the files). However, consider this:

Dim s As String
For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
    Try
        System.IO.File.Delete(s)
    Catch ex As IOException
    End Try
Next s

In this second example, it will jump to the End Try and then continue to the next iteration of the For loop (thereby continuing on the the next file in the list).

Also, as noted in the comments, above, you definitely ought to be using Path.GetTempPath to get the path to the temporary folder. You should not construct the path yourself, since it could change. For instance, Windows does not require that you user folder has to be under C:\Users. You can actually change that.

Upvotes: 1

mbarthelemy
mbarthelemy

Reputation: 12913

Use a Try/Catch block to catch errors (exceptions)

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    If CheckBox1.Checked = True Then
        Dim s As String
        For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
            Try
                System.IO.File.Delete(s)
            Catch ex As Exception
                Console.WriteLine("File could not be deleted : {0}", ex.Message)
            End Try
        Next s
    End If
end sub

That will allow your program to ignore the error and continue processing the next items.

Upvotes: 3

Related Questions