views:

971

answers:

3

What are the API calls to copy a file that is currently locked. I'm hoping to be able to use .Net, but Win32 calls would be fine as well.

Please feel free to chime in about the same functionality on Unix, or any other OS.

+5  A: 

Almost the same as my answer to another question:

If you are on Win32, the official way to do it is to mark it to be moved on reboot, and ask the user to reboot. To mark the file to be moved on reboot, use MoveFileEx with the MOVEFILE_DELAY_UNTIL_REBOOT flag.

It's the same function, only this time you don't pass NULL as the destination.

CesarB
+10  A: 

You can use the VSS (Volume Shadow Copy Service, not Visual SourceSafe) API for this purpose. While powerful, this isn't exactly an easy-to-use API: the Overview of Processing a Backup Under VSS should give you an idea what's involved.

Even though it's a relatively recent API, .NET support for VSS is pretty much (and inexcusably) nonexistent. You can't call most of the API through Interop, and the Framework file functions won't work with the kernel namespace VSS uses to expose the snapshotted files. As a bonus, there are horrendous 32/64-bit and XP-vs-Vista issues, making deployment exciting as well (the responsible team at Microsoft should be really proud!)

Anyway, the AlphaVSS project intends to bring full VSS functionality to .NET, and looks extremely promising, even though it's still in pre-beta stage. It might just do the trick for you, though, and it's open source (Managed C++).

For a good example of how to do things using Win32, see HoboCopy. The utility is quite useful on its own, and full C++ source is available from the SourceForge project page as well.

mdb
+4  A: 

Depending upon what exactly has locked your file, you can either do System.IO.File.Copy(), or create a System.IO.BinaryReader and a System.IO.BinaryWriter and manually create a copy of the file by reading chunks of the locked file and writing them to a new file. I have seen situations where one method was possible but the other wasn't, based on why the file was locked.

This is the "all .NET" answer.

MusiGenesis