-->

Using SHFileOperation within a Windows service

2020-04-20 07:14发布

问题:

It's possible, but is it appropriate to use SHFileOperation within a Windows service? All those SHxxx API functions in shell32.dll seem to have been written with user level programs in mind. Can I be certain SHFileOperation won't display GUI ever?

回答1:

I would say, not it's not appropriate or advisable. Most of the shell32 APIs were written with a basic understanding that they would be used in interactive processes. I don't think there is any way you can guarantee that SHFileOperation will never display a UI component. In fact, if you look at IFileOperation (which is the new Vista interface that replaces SHFileOperation), it clearly states:

Exposes methods to copy, move, rename, create, and delete Shell items as well as methods to provide progress and error dialogs. This interface replaces the SHFileOperation function.



回答2:

According to the SHFILEOPTSTRUCT documentation, you can use the following flags to prevent any UI from appearing:

FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR

or (if you're targeting Windows Vista), FOF_NO_UI, which is the same as the above.

Looking in the ShellAPI.h header file in the Windows SDK, the comment against FOF_NO_UI says "don't display any UI at all", so from this I assume it's OK to use SHFileOperation.



回答3:

I have to agree: not appropriate or advisable.

The prinicpal reason to use SHFileOperation is to perform operations with a UI, and/or which are reversable. I.e. using SHFileOperation to delete files is going to place the files in a recycle bin rather than deleting them allowing the current interactive user to undelete, or undo the operation performed. As the services run on a non interactive desktop, no one will ever be able to clear that recycle bin out.



回答4:

I had this issue as well and working at implementing a secure and reliable network file copy between servers and network shares ( most of these shares are CIFS / NetApp filer based ) and SHFileOperation fails from time to time.

now started using ROBOCOPY (available by default in all Microsoft OS from Vista/Server 2008 upwards) and really looks interesting and reliable.

this has opened my eyes: https://stackoverflow.com/a/1030752/559144