2011-02-10 63 views
0

我通过健康监测创建了一个文件清理功能。它正在删除另一个进程无法访问的文件。所以,我想检查一下。它保持访问。如果不能访问,我删除这个文件。我能怎么做?我怎么知道一个文件正在使用或不在asp.net

+3

错误:这个文件是使用海洛因(asp.net) – 2011-02-10 09:21:51

+0

你的意思是“如何知道一个文件是否正在使用(通过另一个进程)从一个asp.net应用程序?” =) – Rob 2011-02-10 09:24:17

回答

2

一两件事你可以做,而不是试图去检查,看是否有文件被锁定(因为这可能在检查和尝试删除之间的时间变化)是包裹在try/catch块删除尝试:

Dim filenameToDelete = "AFileThatsInuse.doc" 
Try 
    System.IO.File.Delete(filenameToDelete) 
Catch ex As IOException 
    ' Have some code here that logs the content of the exception to a log file, 
    'the Windows Event Log or sends an email - whatever is appropriate 
End Try 

请注意,与捕获通用Exception相比,我抓到了IOException。这是因为documentationFile.Delete状态,你会得到这个异常时:

The specified file is in use.

-or-

There is an open handle on the file, and the operating system is Windows XP or earlier. This open handle can result from enumerating directories and files. For more information, see How to: Enumerate Directories and Files.

您可能仍然想赶上/处理其他异常类型,但它绝不是一个好主意,“盲目地”捕获并处理异常,而不是其更具体的变体之一。

你也可以尝试open the file,并且如果失败,那么您可以告诉该文件已经打开其他地方:

Try 
    System.IO.File.Open("AFileThatsInUse.doc", FileMode.Open, FileAccess.Read, FileShare.None) 
Catch ex as IOException 
    ' As before, what you do when you determine the file is in use is up to you 
End Try 

该代码试图打开该文件完全,所以如果另一进程已经打开文件,它应该失败并且为你扔掉IOException

相关问题