开发者

Hook into the Windows File Copy API from C#

Is there a way to hook into the Windows File Copy API from C#? I'm aware this would require unmanaged code, but a code sample or starter would be helpful. I've already seen the C++ code, but it's all greek.

UPDATE: I apologize, I should have been more clear about my intentions. I wish to actually change the copy feature of Windows to be more rigid (e.g. allow queing, scheduling, handle restarts, pauses, etc.). When I said hook, I meant API hook so that when someone starts a copy I get the sources and destinations and can handle it to my heart's desire. I'm old school and used to hook the Mac OS API a lot to do these th开发者_Go百科ings so I assumed that in the C++ WINAPI world there was some type of equiv.


Update: As others have stated, why not just use System.IO.File.Copy(...)? It calls this same underlying API. As Michael G points out, perhaps you intend to call the the FileCopyEx API that allows you to hook progress-indication callbacks(???) That's really the only reason to P/Invoke file-copy stuff in .NET. Details on how to implement FileCopyEx that can be found here: http://pinvoke.net/default.aspx/kernel32/CopyFileEx.html

Original answer: (which you really shouldn't use...)

Code snippet removed because you really shouldn't use it... If you're hell-bent on making busted-code, you can find out how to use it at: Found at http://pinvoke.net/default.aspx/kernel32/CopyFile.html


I wish to actually change the copy feature of Windows to be more rigid

You shouldn't do that in managed code, because of the same reasons you should not write managed shell extensions.


You can do so by calling System.IO.File.Copy. Its internal implementation already uses the Windows API.

Edit: File.Copy also handles permissions correctly and has the benefit of throwing an exception with meaningful data if something fails, so you don't have to manually check and analyze the return status.


You can use Deviare API Hook that lets you intercept any API from .NET and read parameters using VARIANT types. There is a full example very easy to follow in C#.


The other benefit of using unmanaged Copy File API is the ability to have a progress callback.

Note: as stated in other answers, I would use the managed version of File.Copy as it's safer, and can usually do everything you require.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜