2012-04-20 37 views
1

我创建一个控制台应用程序将从一个目录中删除的照片,每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语句检查如果当前提交其对超过30秒前更新?

OR

有只填充方式:

Dim f() As String = Directory.GetFiles(sourceDir) 

只有那些超过30秒的旧文件?

回答

2

没有,如果一个文件被锁定或不检测的可靠方法。即使您确实发现了(这在技术上是可行的),但在尝试删除它之前可能会被锁定。还有其他原因可能导致删除失败。就你而言,我认为这不重要。

的唯一方法是,将通话中一个try/catch和陷阱IOException异常删除,然后重新尝试,如果你想。

你需要使用一个FileInfo对象来获取CreatedTime,并比较现在。您还可以使用LastAccessTimeLastWriteTime,但由于这些都是被写入所有的新文件,那么,你就不需要。

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 

​​函数从该其他thread on SO

+0

1即IsFileLocked函数是一个宝石! – 2012-04-20 05:15:27

+0

来吧,肯定:)因为你我重写了Linq的文件列表! – 2012-04-20 05:22:00

0
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

+0

我对线的过载抬起** PicFiles.Where(功能(x)的System.IO.File.GetCreationTime(X) StealthRT 2012-04-20 04:14:46

+0

** NewFileDate **需要做什么? – StealthRT 2012-04-20 04:20:45

+0

昏暗NewFileDate作为日期时间= DateTime.Now.AddSeconds(-30) – 2012-04-20 04:22:50

相关问题