最近有同事提出了这个小需求,上班的时候一直没有心思考虑。周末的时候小小的实践了一把。现在贴出来,以后自己可以粘贴代码用。
这个功能很简单,我们常常会用到DeleteFile,但这个API是将文件完全删除而不会保存到回收站中。上网搜了下,大家都推荐使用SHFileOperation这个函数。先给大家看一下MSDN中的解释。如下:
Copies, moves, renames, or deletes a file system object.
Syntax
int SHFileOperation( LPSHFILEOPSTRUCT lpFileOp );
Parameters
lpFileOp
- [in] Pointer to an SHFILEOPSTRUCT structure that contains information this function needs to carry out the specified operation. This parameter must contain a valid value that is not NULL. You are responsibile for validating the value. If you do not validate it, you will experience unexpected results.
Return Value
Returns zero if successful, or nonzero otherwise.
Remarks
You should use fully-qualified path names with this function. Using it with relative path names is not thread safe.
With two exceptions, you cannot use SHFileOperation to move special folders from a local drive to a remote computer by specifying a network path. The exceptions are the My Documents and My Pictures folders (CSIDL_PERSONAL and CSIDL_MYPICTURES, respectively).
When used to delete a file, SHFileOperation permanently deletes the file unless you set the FOF_ALLOWUNDO flag in the fFlags member of the SHFILEOPSTRUCT structure pointed to by lpFileOp. Setting that flag sends the file to the Recycle Bin. If you want to delete a file and guarantee that it is not placed in the Recycle Bin, use DeleteFile.
If a copy callback handler is exposed and registered, SHFileOperation calls it unless you set a flag such as FOF_NOCONFIRMATION in the fFlags member of the structure pointed to by lpFileOp. See ICopyHook::CopyCallback for details on implementing copy callback handlers.
File deletion is recursive unless you set the FOF_NORECURSION flag in lpFileOp.
MSDN写得很多,主要就是说这个函数功能很强大!函数的参数只有一个,再仔细跟一下参数类型:SHFILEOPSTRUCT。 咱们也先看看MSDN的注释,如下:
Contains information that the SHFileOperation function uses to perform file operations.
Syntax
typedef struct _SHFILEOPSTRUCT { HWND hwnd; UINT wFunc; LPCTSTR pFrom; LPCTSTR pTo; FILEOP_FLAGS fFlags; BOOL fAnyOperationsAborted; LPVOID hNameMappings; LPCTSTR lpszProgressTitle; } SHFILEOPSTRUCT, *LPSHFILEOPSTRUCT;
Members
hwnd
- Window handle to the dialog box to display informa