Saturday, January 15, 2011

How to find the application which locked a file

When we deal with any application which does file copy or move we will end up in a scenario where some other application holds our target file and hence we cannot operate on that file.

In a perfect world where everybody codes well,this is not at all an issue.But nothing is perfect. So we need to check whether our target file system object is in use by any other application or process.I used the word file system object particularly because it includes files as well as folders .

Last week I got three queries from different people about the same .That is the reason for this post.

As always there are so many ways .I started with the usual try catch way. Write a method like bool IsLocked(string fileName) which uses a try catch block and inside the try read the file.If exception occurs its locked ie return true else false.

I myself said this hits your performance as each and every time you need to go through a try catch block.Oh what should we do then? I gave them another link which uses unmanaged code to find out the process which locked the file.

http://www.codeguru.com/Cpp/W-P/dll/article.php/c3641/#more
They became happy.

But was that a good solution? If we are trying for perfection will this handle all the possible scenarios? I will say no.Because immediately after you check for the lock and it says no locks some other application may take that file. It may be fraction of seconds .But there is a possibility.So what we can do?

My recommendation is to put all the file related operations in a transaction / try catch where ever appropriate and maintain a log.When one file breaks ,call the routine to find out the process which locked the file and ask the user to shut down that process.If user says ok we can continue else roll back the operations based on our log.

Still there are loop holes.What will happen if a file gets locked when you do the rollback operation? If that file is not a really meant to be used by any process ie your application specific ,kill the process else show the same UI to the user that we are not able even roll back.Still if the user is not willing to shut down his process,its his fate to have an environment which is not correct.

Remember there is no 100% perfection but 99.99%.

No comments: