VHanded
VHanded

Reputation: 2089

How to detect a file is in use?

I had searched a lot of examples, but none work perfect for me. I am using C#.

My application need to remove the files in folder, only when the file is closed.

The try-catch File.Open(...) method only works for certain filetype like doc, xls, ppt, pdf, mp3 etc, but not work for txt, zip, html etc...

Upvotes: 1

Views: 1265

Answers (4)

Mubashir Khan
Mubashir Khan

Reputation: 1494

all you need is to delete the file that is not in use ... rigth ... Simply ignore the exception thrown by File.Delete. Since it will not delete the file that is in use ..

try
{
    File.Delete(path);
}
catch(Exception e)
{
// ignore ... or whatever action
}

you can also catch specific exceptions to take specific action ... like IOException for file in use, UnauthorizedAccessException for read only files and permission issues etc ...

Checking file for opening and then trying to delete may still through exception as file may have been opened by some process between checking and deleting operations ..

Upvotes: 0

Mahesh
Mahesh

Reputation: 1683

Try opening the file in write mode, I think there is something to specify that the lock is exculsive..but for some reason if your thread dies..dunno if that lock will be released automatically...

Upvotes: 0

Josh
Josh

Reputation: 69242

The behavior your are seeing doesn't have anything to do with the file's extension or contents. It has to do with the way the associated applications treat those files. For example, Notepad, Internet Explorer, etc will not hold a lock on an opened file once the contents are read. That's why .txt and .html files are able to be opened.

Microsoft Office, virtually all media players, etc will hold a lock on the file. In the case of Office, it's doing so to make sure other programs don't delete/move the file out from under it. In the case of a media player, the files are usually too big to be read into memory completely. That's why those file types are locked when in use.

In other words, those files that appear to not be in use aren't actually in use. The program read the data from the file and close it and now it's done with it. There's really no easy way to determine whether or not another program has a particular file open if it no longer has an open handle to the file.

Upvotes: 11

Shashi
Shashi

Reputation: 2898

Open the file in the binary mode File.Open(...) will work for all files.

Upvotes: 0

Related Questions