Hook into the Windows File Copy API from C#

六眼飞鱼酱① 提交于 2020-02-01 08:56:30

问题


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 things so I assumed that in the C++ WINAPI world there was some type of equiv.


回答1:


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.




回答2:


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




回答3:


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

You can see an example of how to do so here.

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.




回答4:


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.




回答5:


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#.



来源:https://stackoverflow.com/questions/1590155/hook-into-the-windows-file-copy-api-from-c-sharp

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