我正在创建一个控制台应用程序,它将每隔30分钟从目录中删除图片。问题是它每隔一分钟就会被文件填充。因此,如果我去删除该目录中的文件,则可能会导致尝试删除刚刚创建或打开的文件时出错。
我目前有这段代码将文件复制到另一个目录,然后从源目录中删除它们。
Dim f() As String = Directory.GetFiles(sourceDir)
For i As Integer = 0 To UBound(f)
'Check file date here in IF statement FIRST...
File.Copy(f(i), destDir & f(i).Replace(sourceDir, ""))
If File.Exists(f(i)) = True Then
File.Delete(f(i))
End If
Debug.Print(f(i) & " to >>> " & destDir & f(i).Replace(sourceDir, ""))
Next
我该如何使用:
File.GetCreationTime(f(i))
在IF语句中检查IF当前文件是否比30秒前更新?
或
有没有办法只填充:
Dim f() As String = Directory.GetFiles(sourceDir)
只有那些超过30秒的文件?
答案 0 :(得分:2)
没有可靠的方法来检测文件是否被锁定。即使您确实发现了(技术上可行),也可以在尝试删除它之前将其锁定。删除可能会失败还有其他原因。在你的情况下,我认为原因并不重要。
唯一的方法是在try / catch和trap IOException中调用delete,然后根据需要重试。
您需要使用FileInfo对象获取CreatedTime
并与Now进行比较。您也可以使用LastAccessTime
或LastWriteTime
,但由于这些都是正在编写的新文件,因此您无需使用。
Private Sub DeleteFiles()
Dim files = From f In Directory.GetFiles("c:\temp")
Let fi = New FileInfo(f)
Where fi.Exists AndAlso fi.CreationTime <= DateTime.Now.AddSeconds(-30)
For Each f In files
Try
f.Delete()
Catch ex As Exception
If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then
' do something?
End If
'otherwise we just ignore it. we will pick it up on the next pass
End Try
Next
End Sub
Private Shared Function IsFileLocked(exception As Exception) As Boolean
Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
Return errorCode = 32 OrElse errorCode = 33
End Function
IsFileLocked
函数已从其他thread on SO
答案 1 :(得分:1)
Dim NewFileDate As DateTime = DateTime.Now.AddSeconds(-30)
' get the list of all files in FileDir
Dim PicFiles As List(Of String) = System.IO.Directory.GetFiles("C:\", "*.txt").ToList()
' filter the list to only include files older than NewFileDate
Dim OutputList As List(Of String) = PicFiles.Where(Function(x) System.IO.File.GetCreationTime(x) < NewFileDate).ToList()
' delete files in the list
For Each PicFile As String In OutputList
'wrap this next line in a Try-Catch if you find there is file locking.
System.IO.File.Delete(PicFile)
Next
显然是针对.Net 3.5或4.0