SHFileOperation Function
BOOL SHFileOperation(
[in, out] LPSHFILEOPSTRUCT lpFileOp
);
Syntax
The SHFileOperation function performs various file operations, such as copying, moving, renaming, or deleting files and directories.
Parameters
-
lpFileOp
Type:LPSHFILEOPSTRUCT
A pointer to aSHFILEOPSTRUCTstructure that contains all the information needed for the operation.
Return Value
-
TRUEif the operation was successful.
FALSEif the operation failed.
For more detailed error information, use GetLastError. Common error codes include:
ERROR_SUCCESS(0): The operation completed successfully.ERROR_FILE_NOT_FOUND(2): The specified source file or directory was not found.ERROR_PATH_NOT_FOUND(3): The specified destination path was not found.ERROR_ACCESS_DENIED(5): Access to the source or destination was denied.ERROR_CANCELLED(1223): The operation was cancelled by the user.
Remarks
This function handles common file operations, providing a user-friendly interface and handling potential conflicts or errors.
- The function can perform the following operations, specified by the
wFuncmember of theSHFILEOPSTRUCTstructure:FO_COPY: Copy files.FO_MOVE: Move files.FO_DELETE: Delete files.FO_RENAME: Rename files.FO_EXEC: Execute a file.FO_CREATE: Create a new directory.FO_DELETE_PERMANENT: Permanently delete files (bypass Recycle Bin).
- The
dwFlagsmember ofSHFILEOPSTRUCTallows for customization of the operation, such as enabling or disabling prompts, specifying Recycle Bin behavior, and more. - When performing a copy or move operation, the
pFrommember should point to a null-terminated string containing the source file path, andpToshould point to a null-terminated string containing the destination path. For operations on multiple files (e.g., deleting multiple files), both strings should be null-terminated strings separated by a double null terminator (\0\0). - The
wFuncmembersFO_COPY,FO_MOVE, andFO_RENAMEcan be combined withFOF_RENAMEONCOLLISIONto automatically rename files if a conflict occurs at the destination.
Requirements
The following table shows the minimum requirements for this function:
| Attribute | Value |
|---|---|
| Minimum supported client | Windows 2000 Professional |
| Minimum supported server | Windows 2000 Server |
| Header | shellapi.h |
| Library | Shell32.lib |
| DLL | Shell32.dll |
Example
#include <windows.h>
#include <shellapi.h>
#include <iostream>
int main() {
SHFILEOPSTRUCT fileOp;
ZeroMemory(&fileOp, sizeof(SHFILEOPSTRUCT));
// Example: Delete a file
const WCHAR* sourceFilePath = L"C:\\path\\to\\your\\file.txt";
fileOp.wFunc = FO_DELETE;
fileOp.pFrom = sourceFilePath;
fileOp.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; // Allow undo, no confirmation
int result = SHFileOperation(&fileOp);
if (result == 0) {
std::wcout << L"File operation successful." << std::endl;
} else {
std::wcout << L"File operation failed. Error code: " << result << std::endl;
// You might want to call GetLastError() for more specific error info
}
return 0;
}