zanhtet
zanhtet

Reputation: 2050

How can I know that a file is using or not in asp.net

I created a file cleanup function by using health monitoring. It is deleting file that is no access from another process. So, I want to check this. Is it stay access. If not access, I delete this file. How can I do?

Upvotes: 0

Views: 742

Answers (1)

Rob
Rob

Reputation: 45780

One thing you can do, rather than trying to check to see if a file is locked (as this could change in the time between checking and attempting to delete) is wrap the delete attempt in a try/catch block:

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

Note that, rather than catching the generic Exception, I've caught IOException. This is because the documentation for File.Delete states that you'll get this exception when:

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.

You may still want to catch/handle other exception types but it's never a good idea to "blindly" catch and handle Exception, rather than one of its more specific variants.

You could also attempt to open the file to write, and if that fails then you can tell that the file is already open elsewhere:

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

This code attempts to open the file exclusively, so if another process has the file open already, it should fail and throw the IOException for you.

Upvotes: 2

Related Questions