1

我正在尝试以编程方式清除我的临时文件夹,但是它无法删除正在使用的文件,只要它会删除所有未使用的文件就可以了。但是,我的代码基本上要求我们删除全部或不删除,而不仅仅是那些未使用的。

下面是代码有人可以告诉我如何解决这个问题吗?

   '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
4

1 回答 1

4

您可以使用简单的 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
于 2012-10-02T08:02:07.633 回答