无法通过SHGetKnownFolderPath获取回收站路径,求非硬编码解决方案
解决无法通过SHGetKnownFolderPath获取回收站路径的问题
回收站没有对应的官方KNOWNFOLDERID,所以SHGetKnownFolderPath无法直接获取其路径。你可以通过以下两种替代方案实现,避免硬编码路径:
方案一:使用SHGetSpecialFolderLocation + SHGetPathFromIDList
这是兼容新旧Windows版本的经典方法,通过CSIDL_BITBUCKET标识回收站:
#include <shlobj.h> #include <stdexcept> #include <string> #include <memory> // 自定义内存释放器,适配CoTaskMemFree struct CoTaskMemDeleter { void operator()(void* p) const { CoTaskMemFree(p); } }; static std::string GetRecycleBinPath(const char* errorMsg) { LPITEMIDLIST pidl = nullptr; HRESULT hr = SHGetSpecialFolderLocation(nullptr, CSIDL_BITBUCKET, &pidl); std::unique_ptr<ITEMIDLIST, CoTaskMemDeleter> pidlGuard(pidl); if (!SUCCEEDED(hr)) { throw std::runtime_error(errorMsg); } WCHAR wszPath[MAX_PATH] = {0}; if (!SHGetPathFromIDListW(pidl, wszPath)) { throw std::runtime_error(errorMsg); } return sago::internal::win32_utf16_to_utf8(wszPath); }
方案二:使用SHGetFolderPath(过时但仍可用)
SHGetFolderPath是SHGetSpecialFolderLocation的封装,同样支持CSIDL_BITBUCKET:
#include <shlobj.h> #include <stdexcept> #include <string> static std::string GetRecycleBinPath(const char* errorMsg) { WCHAR wszPath[MAX_PATH] = {0}; HRESULT hr = SHGetFolderPathW(nullptr, CSIDL_BITBUCKET, nullptr, 0, wszPath); if (!SUCCEEDED(hr)) { throw std::runtime_error(errorMsg); } return sago::internal::win32_utf16_to_utf8(wszPath); }
注意事项
- 上述方法获取的是当前用户专属的回收站路径(格式为
C:\$Recycle.Bin\<用户SID>),而非根目录下的$Recycle.Bin,更符合实际使用场景。 CSIDL_BITBUCKET在Windows Vista及以后被标记为过时,但微软并未移除该接口,仍可在所有现代Windows系统中正常工作。
内容的提问来源于stack exchange,提问作者Ashutosh Jha
相关产品推荐
相关产品推荐

