如何通过Windows C++ API编程恢复回收站文件(支持自定义路径)
Windows C++ 实现回收站文件恢复(支持自定义路径)
要实现从回收站恢复文件,核心是将回收站中对应的条目文件(即示例中的$RJB4I8F)移动到目标路径(原路径或自定义路径)。以下是具体实现方案,包含错误处理和目录创建逻辑:
核心实现步骤
- 确保目标路径的父目录存在,不存在则递归创建
- 使用Windows API移动回收站条目到目标路径,处理文件冲突等异常情况
完整代码示例
#include <windows.h> #include <shlwapi.h> #include <iostream> #pragma comment(lib, "shlwapi.lib") // 递归创建目录 bool CreateDirectoryRecursive(LPCWSTR path) { WCHAR tempPath[MAX_PATH]; wcscpy_s(tempPath, path); // 遍历路径中的每个目录段 for (WCHAR* p = tempPath; *p; p++) { if (*p == L'\\' || *p == L'/') { *p = L'\0'; // 如果目录不存在则创建 if (!PathFileExistsW(tempPath) && !CreateDirectoryW(tempPath, NULL)) { *p = L'\\'; return false; } *p = L'\\'; } } // 创建最后一级目录 if (!PathFileExistsW(tempPath) && !CreateDirectoryW(tempPath, NULL)) { return false; } return true; } // 恢复回收站文件到目标路径 bool RestoreRecycleBinFile(LPCWSTR recycleBinItemPath, LPCWSTR targetPath) { // 1. 验证回收站条目是否存在 if (!PathFileExistsW(recycleBinItemPath)) { std::wcerr << L"回收站条目不存在: " << recycleBinItemPath << std::endl; return false; } // 2. 获取目标路径的父目录并创建 WCHAR parentDir[MAX_PATH]; wcscpy_s(parentDir, targetPath); if (!PathRemoveFileSpecW(parentDir)) { std::wcerr << L"无效的目标路径: " << targetPath << std::endl; return false; } if (!CreateDirectoryRecursive(parentDir)) { std::wcerr << L"创建父目录失败,错误码: " << GetLastError() << std::endl; return false; } // 3. 移动文件到目标路径,支持覆盖已存在文件 if (!MoveFileExW(recycleBinItemPath, targetPath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED)) { std::wcerr << L"移动文件失败,错误码: " << GetLastError() << std::endl; return false; } return true; } int main() { // 原文件路径 wchar_t const* original_path = L"C:\\code\\swan\\ignore\\dir_2\\file1"; // 回收站条目路径 wchar_t const* recycle_bin_path = L"C:\\$Recycle.Bin\\S-1-5-21-738277947-893724712-3765747123-1001\\$RJB4I8F"; // 自定义目标路径(示例) wchar_t const* custom_target_path = L"D:\\recovered\\file1_restored.txt"; // 恢复到原路径 if (RestoreRecycleBinFile(recycle_bin_path, original_path)) { std::wcout << L"成功恢复到原路径: " << original_path << std::endl; } // 恢复到自定义路径 if (RestoreRecycleBinFile(recycle_bin_path, custom_target_path)) { std::wcout << L"成功恢复到自定义路径: " << custom_target_path << std::endl; } return 0; }
关键细节说明
- 回收站条目说明:回收站中的
$R开头的文件是被删除文件的实际内容,$I开头的是包含原路径、删除时间等信息的元数据文件。恢复时只需要操作$R开头的文件即可。 - 权限要求:程序需要以足够权限运行(比如管理员权限),否则可能无法访问
$Recycle.Bin目录。 - 错误处理:代码中通过
GetLastError()获取具体错误码,常见错误包括权限不足、文件已被占用、路径不存在等。 - 移动选项:
MOVEFILE_REPLACE_EXISTING允许覆盖目标路径已存在的文件,MOVEFILE_COPY_ALLOWED在跨卷移动时自动转为复制+删除操作。
内容的提问来源于stack exchange,提问作者nluka
相关产品推荐
相关产品推荐

