Tuesday, April 21, 2009

Nifty file utility that every developer can use

Here's a scenario faced by practically every developer at one time or another:  you want to delete a file, but it refuses to delete because Windows sees the file as "locked" by another user.

Sometimes this can be a real file lock, when a user on a different computer does actually have the file open, or sometimes it can be file-locking "junk" left over when a computer that did have a lock crashed or suddenly closed an application.

There has never been a simple "unlock" command to get rid of the file lock (in order to delete the file), no matter why it's being locked, leading to a cavalcade of utilities to work around the problem. 

The classic utilities that you'll come across when searching for keywords like "force delete" are programs that delete the locked file at the next boot.

But what a pain in the neck that is!  I refuse to install one of those programs, because I always have many programs running, and a fresh boot, done merely to delete a file, is just too painful.

Over the years this issue has been a major gripe with me, which is why I was so happy to finally find a good solution this evening.  And the thing is that the utility has been around since 2006.

The utility is called PsFile, and is a part of the brilliant SysInternals suite of utilities created by Mark Russinovich. 

Frustratingly, I've looked through SysInternals in the past seeking this same solution, but I always overlooked PsFile because the option to do the unlocking is so subtlely mentioned in the documentation.  It comes off as a utility merely to see who has a file open — not a utility to actually close the file/lock.

In my frustration of trying to unlock a file this evening, I had downloaded PsFile just to give me an idea of who/what was holding the lock.  I ran the program and saw the file lock, but then looking back at the documentation I noticed a little "-c" command line option.  The documentation states, "-c : Closes the files identified by ID or path."  Wow!

I gave the option a try, specifying the ID number of the file (which was shown simply by typing "PsFile" at the command prompt), and the file was instantly closed.  Awesome!

The exact syntax of the unlock is:

PsFile 1234 -c       (1234 is replaced by the actual file ID, or can be a path name)

The PsFile utility can be found (and downloaded) here: http://technet.microsoft.com/en-us/sysinternals/bb897552.aspx

One of the things I love about all the SysInternals utilities is that there is no installation needed.  Just unzip the download and copy the included .exe file to your hard disk, and then run it.

SysInternals is extensive and indispensable, and its home page can be found here: http://technet.microsoft.com/en-us/sysinternals/bb842062.aspx

I hope this helps anyone who's experienced a similar problem!