How do I copy a file or folder that is locked under windows programmatically?

坚强是说给别人听的谎言 提交于 2019-11-30 17:50:25

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.

CesarB

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!