How to ensure the replacement of files in a directory?
I want to completely replace one directory in the filesystem with another directory in the temp directory. The tricky part is that the files in the folder to be replaced can be used at any time, causing the replace operation to fail.
I need to somehow wait for an exclusive lock on a directory so that I can delete all of its contents without crashing, so I can move another directory to replace it.
To make things more complicated, the process that is likely to use the files is my own (via the Lucene.net library and out of my hands). So it cannot be a process-level lock, it must be an object-level lock.
Any thoughts on how I can accomplish this? Or should I just keep trying again until it succeeds? I guess it's always an option.
a source to share
A utility InUse.exe
from Microsoft will do this, but restarting your computer requires you to restart your computer. More information: http://support.microsoft.com/kb/228930
Usage example:
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. a source to share
SLaks answer is wrong, you cannot rename an entire directory if it contains files that are in use.
However, you can rename or move files that are in use. I don't know if this works in all versions of Windows, but I know it is for sure in Windows 7. If the program is open, it will remain open, but if something tries to open the file after being moved, it will obviously no longer.
So you can use this to replace the executable executable, but if the executable tries to load one of the DLLs it depended on, which it was also moved on, the application will crash for the end user.
Depending on what you are trying to replace, you can create a directory for possible deletion, move each file that needs to be replaced to that directory, copy the new file, and when you're done, try to delete every file in the temp directory. Then, if there are any files, you can mark them for possible deletion with this:
"MoveFile" function in C # (delete file after reboot)
After further experimentation, I found that you can move files that are in use, but only under certain circumstances. If you open the file with access to the "ShareDelete" file, it works. It also works with running executables and dlls ... they can be moved around even if they cannot be deleted. But a file that was opened normally (eg with "File.OpenRead ()") will still use the "file in use" IOException.
a source to share