开发者

Is DirectoryInfo.LastWriteTime a safe way to check that a file isn't still uploading?

Is it safe to use something like this to ensure that a directory isn't currently being written to?

Dim ImportDir As New DirectoryInfo("C:\MyPath\")
If DateDiff(DateInterval.Minute, ImportDir.LastWriteTime, Now) < 10 Then
    Exit Sub
End If

I'm processing images which can be up to 10MB so my main 开发者_C百科concern is that I'm not sure whether the LastWriteTime property (which presumably references the filesystem 'last modified' meta data) is updated when the first, last or every byte of a file is written to disk.

Files will generally be uploaded via IIS7 FTP to an NTFS Filesystem on a Windows 2008 server. If it's filesystem-dependant though it would be good to also know which filsystems update when.

EDIT: I'd hoped that this could be used to simplify the programme by ensuring that the whole directory was processed at once. In the end I decided to rethink that since the workarounds are messier and less reliable than the one I was trying to avoid! Cheers for the answers though


Not at all. LastWriteTime is updated after writing, not while writing. You need to rely on whatever program is doing the uploading to put a lock on the file. Any decent one does. So that trying to open the file with, say, the FileStream constructor with FileShare.Read or FileShare.None will throw an IOException. This will almost always work.


I'm not entirely sure how accurate your method would be. However, an alternative solution would be to attempt to open the file in exclusive mode (FileShare.None) within a try-catch, e.g.

Dim fs As FileStream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None);

(Obviously place it inside a try-catch)

While this is generally considered coding by exception, it does provide an alternative to ensure that the file isn't locked by another process.


You will find a good answer on checking to see if a File is accessible here: How to check for file lock? as it's a common problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜