LabRat
LabRat

Reputation: 2014

Deleting temp folder files with vb.net

I’m trying to programmatically clear out my temps folder however it can't delete files that are in use, which would be okay as long as it would then delete all the files not in use. However my code basically demands either we delete all or none, not just those not in use.

Below is the code could anybody please tell me how I can work around this?

   'Deletes files in temporary directory...
    Dim MYDAYS_2 As String
    Dim MYTEMPFOLDER As String = System.IO.Path.GetTempPath

    'this reads the regestry key otherwise gives a default value in its place (365)...
    MYDAYS_2 = Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\AA", "HELLO", "365")

    'Deletes all files older then the day specifyed in the variable MDAYS...
    For Each file As IO.FileInfo In New IO.DirectoryInfo(MYTEMPFOLDER).GetFiles("*.*")
        If (Now - file.CreationTime).Days > MYDAYS_2 Then file.Delete()
    Next

Upvotes: 1

Views: 8418

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

You could use a simple try/catch:

For Each file As IO.FileInfo In New IO.DirectoryInfo(MYTEMPFOLDER).GetFiles("*.*")
    If (Now - file.CreationTime).Days > MYDAYS_2 Then 
        Try
            file.Delete()
        Catch
            ' log exception or ignore '
        End Try
    End If
Next

Upvotes: 4

Related Questions