views:

69

answers:

2

I want to completely replace one directory on the file system with another directory in a temp directory. The tricky part is that the files in the folder to be replaced could be being used at any time, causing the replace operation to fail.

I need to somehow wait on an exclusive lock on the directory so that I can delete all of its contents without failing, so I can then move the other directory in to replace it.

To make matters potentially more difficult, the process that is likely to be using the files is my own (via a Lucene.net library and out of my hands). So it can't be a process-level lock it has to be an object-level lock.

Any thoughts on how I might do this? Or should I just keep re-attempting until it succeeds? I guess that's always an option.

A: 

If you're replacing the entire directory, you can rename the original directory, then rename to new one to the original name.

SLaks
Is this actually possible? I assumed that would fail if files inside the directory were locked.
chaiguy
If the files are in use, you need to unlock them first. There is no way to modify or replace a locked file without unlocking it.
SLaks
It seems to me if I could just rename the directory, I wouldn't have any trouble replacing it to begin with. Ideally I'd like to just wait for any other usage to cease before deleting it, but are you saying there's a way I can force it to be deleted even if files in it are in use elsewhere?
chaiguy
Not that I know of. You could forcibly close that handles, but that's probably not a good idea.
SLaks
+1  A: 

The InUse.exe utility from Microsoft will accomplish this, however it requires that the computer be restarted for the changes to take effect. More information: http://support.microsoft.com/kb/228930

Example usage:

c:\Program Files (x86)\Resource Kit>inuse C:\temp\new C:\temp\old /y
InUse - version 1.4
---------------------------------------------------------------------------
Copyright (c) 1994-1999 Microsoft Corporation. All rights reserved
Windows 2000 detected - WFP is enforced
Confirmation suppressed

INUSE is about to replace the following file

        Existing:    C:\temp\old
        No version info available

        Replacement: C:\temp\new
        No version info available

        C:\temp\new is replacing --> C:\temp\old

Changes will not take affect until you reboot.
umbyersw
Hmm, that's interesting. Unfortunately requiring a restart makes this not feasible for me, but thanks anyway.
chaiguy