UINT RenameDir(MSIHANDLE hModule, const WCHAR *pwszDestDir, const WCHAR *pwszSourceDir) { UINT rc; WCHAR wszDest[_MAX_PATH + 1]; WCHAR wszSource[_MAX_PATH + 1]; swprintf_s(wszDest, RT_ELEMENTS(wszDest), L"%s%c", pwszDestDir, '\0'); swprintf_s(wszSource, RT_ELEMENTS(wszSource), L"%s%c", pwszSourceDir, '\0'); SHFILEOPSTRUCTW s = {0}; s.hwnd = NULL; s.wFunc = FO_RENAME; s.pTo = wszDest; s.pFrom = wszSource; s.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_NOERRORUI; logStringW(hModule, L"RenameDir: DestDir=%s, SourceDir=%s", wszDest, wszSource); int r = SHFileOperationW(&s); if (r != 0) { logStringW(hModule, L"RenameDir: Rename operation returned status 0x%x", r); rc = ERROR_GEN_FAILURE; } else rc = ERROR_SUCCESS; return rc; }
/////////////////////////////////////////////////////////////// // // DelTree // // // /////////////////////////////////////////////////////////////// bool SharedUtil::DelTree ( const SString& strPath, const SString& strInsideHere ) { // Safety: Make sure strPath is inside strInsideHere WString wstrPath = FromUTF8( strPath ); WString wstrInsideHere = FromUTF8( strInsideHere ); if ( !wstrPath.BeginsWithI( wstrInsideHere ) ) { assert ( 0 ); return false; } DWORD dwBufferSize = ( wstrPath.length() + 3 ) * sizeof( wchar_t ); CScopeAlloc < wchar_t > szBuffer( dwBufferSize ); memset ( szBuffer, 0, dwBufferSize ); wcsncpy ( szBuffer, wstrPath, wstrPath.length() ); SHFILEOPSTRUCTW sfos; sfos.hwnd = NULL; sfos.wFunc = FO_DELETE; sfos.pFrom = szBuffer; // Double NULL terminated sfos.pTo = NULL; sfos.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT | FOF_ALLOWUNDO; int status = SHFileOperationW(&sfos); return status == 0; }
static int rename_file(lua_State *L) { std::filesystem::path fo; std::filesystem::path fn; try { fo = std::filesystem::u8path(luaL_checkstring(L, -2)); fn = std::filesystem::u8path(luaL_checkstring(L, -1)); } catch (...) { return 0; } SHFILEOPSTRUCTW ls; WCHAR buff[MAX_PATH + 1]; WCHAR buff2[MAX_PATH + 1]; ::ZeroMemory(&ls, sizeof(SHFILEOPSTRUCTW)); ::ZeroMemory(buff, MAX_PATH + 1); ::ZeroMemory(buff2, MAX_PATH + 1); wcscpy(buff2, fn.c_str()); wcscpy(buff, fo.c_str()); ls.pFrom = buff; ls.pTo = buff2; ls.wFunc = FO_RENAME; ls.fFlags = FOF_SILENT | FOF_NOCONFIRMATION; // FOF_NOERRORUI | lua_pushnumber(L, SHFileOperationW(&ls)); return 1; }
// 删除目录及文件 BOOL CHistoryManagerXP::DeleteDir(CStringW dir) { SHFILEOPSTRUCTW FileOp; FileOp.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR; FileOp.hNameMappings = NULL; FileOp.hwnd = NULL; FileOp.lpszProgressTitle = NULL; FileOp.pFrom = dir; FileOp.pTo = NULL; FileOp.wFunc = FO_DELETE; return SHFileOperationW(&FileOp) == 0; }
JNIEXPORT void JNICALL Java_org_gudy_azureus2_platform_win32_access_impl_AEWin32AccessInterface_moveToRecycleBinW( JNIEnv *env, jclass cla, jstring _fileName ) { WCHAR file_name[16000]; SHFILEOPSTRUCTW opFile; if ( !jstringToCharsW( env, _fileName, file_name, sizeof( file_name )-1)){ return; } HANDLE file = CreateFileW ( file_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); // Checks if file exists if ( file == INVALID_HANDLE_VALUE ){ throwException( env, "moveToRecycleBin", "file not found" ); return; } CloseHandle(file); file_name[ wcslen(file_name)+1 ] = 0; ZeroMemory(&opFile, sizeof(opFile)); opFile.wFunc = FO_DELETE; opFile.pFrom = file_name; opFile.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT; if (SHFileOperationW (&opFile)){ throwException( env, "moveToRecycleBin", "SHFileOperation failed" ); } }
/************************************************************************** * ISF_Fonts_IContextMenu_InvokeCommand() */ static HRESULT WINAPI ISF_Fonts_IContextMenu2_InvokeCommand( IContextMenu2 *iface, LPCMINVOKECOMMANDINFO lpcmi) { SHELLEXECUTEINFOW sei; PIDLFontStruct * pfont; SHFILEOPSTRUCTW op; IGenericSFImpl * This = impl_from_IContextMenu2(iface); TRACE("(%p)->(invcom=%p verb=%p wnd=%p)\n",This,lpcmi,lpcmi->lpVerb, lpcmi->hwnd); if (lpcmi->lpVerb == MAKEINTRESOURCEA(1) || lpcmi->lpVerb == MAKEINTRESOURCEA(2) || lpcmi->lpVerb == MAKEINTRESOURCEA(7)) { ZeroMemory(&sei, sizeof(sei)); sei.cbSize = sizeof(sei); sei.hwnd = lpcmi->hwnd; sei.nShow = SW_SHOWNORMAL; if (lpcmi->lpVerb == MAKEINTRESOURCEA(1)) sei.lpVerb = L"open"; else if (lpcmi->lpVerb == MAKEINTRESOURCEA(2)) sei.lpVerb = L"print"; else if (lpcmi->lpVerb == MAKEINTRESOURCEA(7)) sei.lpVerb = L"properties"; pfont = _ILGetFontStruct(This->apidl); sei.lpFile = pfont->szName + pfont->offsFile; if (ShellExecuteExW(&sei) == FALSE) return E_FAIL; } else if (lpcmi->lpVerb == MAKEINTRESOURCEA(4)) { FIXME("implement font copying\n"); return E_NOTIMPL; } else if (lpcmi->lpVerb == MAKEINTRESOURCEA(6)) { ZeroMemory(&op, sizeof(op)); op.hwnd = lpcmi->hwnd; op.wFunc = FO_DELETE; op.fFlags = FOF_ALLOWUNDO; pfont = _ILGetFontStruct(This->apidl); op.pFrom = pfont->szName + pfont->offsFile; SHFileOperationW(&op); } return S_OK; }
bool VT::delete_file_folder(std::wstring path) { SHFILEOPSTRUCTW fileOp = {0}; // Double null-terminated string path.push_back(L'\0'); path.push_back(L'\0'); fileOp.fFlags = FOF_NO_UI; fileOp.pFrom = path.c_str(); fileOp.wFunc = FO_DELETE; fileOp.hwnd = NULL; return (SHFileOperationW(&fileOp) == 0); }
bool EraseItemSafe(const char *szFilename) { char Filename[_MAX_PATH+1]; SCopy(szFilename, Filename, _MAX_PATH); Filename[SLen(Filename)+1]=0; SHFILEOPSTRUCTW shs; shs.hwnd=0; shs.wFunc=FO_DELETE; shs.pFrom=GetWideChar(Filename); shs.pTo=NULL; shs.fFlags=FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT; shs.fAnyOperationsAborted=false; shs.hNameMappings=0; shs.lpszProgressTitle=NULL; return !SHFileOperationW(&shs); }
VError XWinFolder::MoveToTrash() const { // don't use XWinFullPath because SHFileOperation fails on any path prefixed with "\\?\". // the path parameter is actually a paths list and must be double null terminated. // so one must copy the path in a temp buffer. UniChar *path = (UniChar*) calloc( fOwner->GetPath().GetPath().GetLength() + 2, sizeof( UniChar)); if (path == NULL) return MAKE_NATIVE_VERROR( ERROR_NOT_ENOUGH_MEMORY); wcscpy( path, fOwner->GetPath().GetPath().GetCPointer()); SHFILEOPSTRUCTW info; memset( &info, 0, sizeof(info)); info.fFlags |= FOF_SILENT; // don't report progress info.fFlags |= FOF_NOERRORUI; // don't report errors info.fFlags |= FOF_NOCONFIRMATION; // don't confirm delete info.fFlags |= FOF_ALLOWUNDO; // move to recycle bin info.fFlags |= FOF_NOCONFIRMMKDIR; info.fFlags |= FOF_RENAMEONCOLLISION; info.wFunc = FO_DELETE; // required: delete operation info.pTo = NULL; // must be NULL info.pFrom = path; VError err; int result = SHFileOperationW( &info); if (result != 0) { // unfortunately, GetLastError() is unusable here. // and the result code is poorly documented. switch( result) { case 0x7C /*DE_INVALIDFILES*/: err = MAKE_NATIVE_VERROR( ERROR_PATH_NOT_FOUND); break; default: err = MAKE_NATIVE_VERROR( ERROR_INVALID_PARAMETER); break; } } else { err = VE_OK; } free( path); return err; }
static bool rmtree(LPCWSTR path) { SHFILEOPSTRUCTW op; WCHAR buf[4*MAX_PATH + 2] = {0}; if (GetFullPathName(path, 4*MAX_PATH, buf, NULL) == 0) return false; op.hwnd = NULL; op.wFunc = FO_DELETE; op.pFrom = buf; op.pTo = NULL; op.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMMKDIR; op.fAnyOperationsAborted = false; op.hNameMappings = NULL; op.lpszProgressTitle = NULL; return SHFileOperationW(&op) == 0; }
int delete_dir_recursively(const QString& path_in) { qWarning ("removing folder %s\n", toCStr(path_in)); #if defined(Q_OS_WIN32) const QString path = QDir::toNativeSeparators(QDir::cleanPath(path_in)); if (path.length() <= 3) { // avoid errornous delete drives like C:/ D:/ E:/ return -1; } int len = path.length(); wchar_t *wpath = new wchar_t[len + 2]; wcscpy(wpath, path.toStdWString().c_str()); wpath[len + 1] = L'\0'; SHFILEOPSTRUCTW fileop; fileop.hwnd = NULL; // no status display fileop.wFunc = FO_DELETE; // delete operation fileop.pFrom = wpath; // source file name as double null terminated string fileop.pTo = NULL; // no destination needed fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT; // do not prompt the user fileop.fAnyOperationsAborted = FALSE; fileop.lpszProgressTitle = NULL; fileop.hNameMappings = NULL; int ret = SHFileOperationW(&fileop); delete []wpath; if (ret == 0) { return 0; } else { return -1; } return 0; #else return posix_rmdir(path_in); #endif }
UINT ExecRemoveDataDirectory(wchar_t *dir) { /* Strip stray backslash */ DWORD len = (DWORD)wcslen(dir); if(len > 0 && dir[len-1]==L'\\') dir[len-1] = 0; SHFILEOPSTRUCTW fileop; fileop.hwnd= NULL; /* no status display */ fileop.wFunc= FO_DELETE; /* delete operation */ fileop.pFrom= dir; /* source file name as double null terminated string */ fileop.pTo= NULL; /* no destination needed */ fileop.fFlags= FOF_NOCONFIRMATION|FOF_SILENT; /* do not prompt the user */ fileop.fAnyOperationsAborted= FALSE; fileop.lpszProgressTitle= NULL; fileop.hNameMappings= NULL; return SHFileOperationW(&fileop); }
/*static*/ unsigned int CRhoFile::deleteFolder(const char* szFolderPath) { #if defined(WINDOWS_PLATFORM) && !defined(OS_WP8) StringW swPath; convertToStringW(szFolderPath, swPath); wchar_t* name = new wchar_t[ swPath.length() + 2]; swprintf(name, L"%s%c", swPath.c_str(), '\0'); translate_wchar(name, L'/', L'\\'); SHFILEOPSTRUCTW fop = {0}; fop.hwnd = NULL; fop.wFunc = FO_DELETE; fop.pFrom = name; fop.pTo = NULL; fop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR #if defined(OS_WINDOWS_DESKTOP) || defined(OS_PLATFORM_MOTCE) | FOF_NOERRORUI #endif ; int result = SHFileOperationW(&fop); delete name; return result == 0 ? 0 : (unsigned int)-1; #elif defined(OS_WP8) StringW swPath; convertToStringW(szFolderPath, swPath); recursiveDeleteDirectory(swPath); return 0; #elif defined (OS_ANDROID) RemoveFileFunctor funct(szFolderPath); return funct(""); #else rho_file_impl_delete_folder(szFolderPath); return 0; #endif }
/// <summary> /// Deletes all selected files. /// </summary> void TileGroup::DeleteSelectedFiles() { // Generate a double-null terminated list of files to copy. DoubleNullStringList files; WCHAR buffer[MAX_PATH]; for (Tile *tile : mTiles) { if (tile->IsSelected()) { tile->GetDisplayName(SHGDN_FORPARSING, buffer, _countof(buffer)); files.Push(buffer); } } // Delete the files. SHFILEOPSTRUCTW shFileOp; ZeroMemory(&shFileOp, sizeof(shFileOp)); shFileOp.wFunc = FO_DELETE; shFileOp.hwnd = nullptr; shFileOp.pFrom = files.GetStringList(); shFileOp.pTo = nullptr; shFileOp.fFlags = FOF_ALLOWUNDO | FOF_WANTNUKEWARNING; SHFileOperationW(&shFileOp); }
static int delete_file(lua_State *L) { std::filesystem::path f; try { f = std::filesystem::u8path(luaL_checkstring(L, 1)); } catch (...) { return 0; } SHFILEOPSTRUCTW ls; WCHAR buff[MAX_PATH + 1]; ::ZeroMemory(&ls, sizeof(SHFILEOPSTRUCTW)); ::ZeroMemory(buff, MAX_PATH+1); wcscpy(buff, f.c_str()); ls.pFrom = buff; ls.wFunc = FO_DELETE; ls.fFlags = FOF_SILENT | FOF_ALLOWUNDO | FOF_NOCONFIRMATION; // FOF_NOERRORUI | lua_pushnumber(L, SHFileOperationW(&ls)); return 1; }
/// <summary> /// Attempts to paste the contents of the clipboard to the desktop /// </summary> void TileGroup::DoPaste() { if (IsClipboardFormatAvailable(CF_HDROP)) { if (OpenClipboard(mWindow->GetWindowHandle())) { LPDROPFILES data = LPDROPFILES(GetClipboardData(CF_HDROP)); bool move = false; WCHAR target[MAX_PATH]; // Check if the file should be moved rather than copied. UINT cfDropEffect = RegisterClipboardFormat(CFSTR_PREFERREDDROPEFFECT); if (IsClipboardFormatAvailable(cfDropEffect)) { move = (*(DWORD*)GetClipboardData(cfDropEffect) & DROPEFFECT_MOVE) == DROPEFFECT_MOVE; } GetFolderPath(target, _countof(target)); // TODO::Handle data->fWide == 0 SHFILEOPSTRUCTW shFileOp; ZeroMemory(&shFileOp, sizeof(shFileOp)); shFileOp.wFunc = move ? FO_MOVE : FO_COPY; shFileOp.hwnd = mWindow->GetWindowHandle(); shFileOp.pFrom = LPCWSTR((BYTE*)data + data->pFiles); shFileOp.pTo = target; shFileOp.fFlags = FOF_NOCONFIRMMKDIR; SHFileOperationW(&shFileOp); if (move && !shFileOp.fAnyOperationsAborted) { EmptyClipboard(); } CloseClipboard(); } } else if (IsClipboardFormatAvailable(CF_TEXT)) { } else if (IsClipboardFormatAvailable(CF_BITMAP)) { } else if (IsClipboardFormatAvailable(CF_WAVE)) { } }
//################################################################## // See DeleteDirectoryA //################################################################## BOOL DeleteDirectoryW(LPCWSTR lpszDir) { size_t len = lstrlenW(lpszDir); WCHAR *pszFrom = new WCHAR[len+2]; lstrcpyW(pszFrom, lpszDir); pszFrom[len] = 0; pszFrom[len+1] = 0; // Append extra NUL SHFILEOPSTRUCTW fileop; fileop.hwnd = NULL; fileop.wFunc = FO_DELETE; fileop.pFrom = pszFrom; fileop.pTo = NULL; fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT; fileop.fAnyOperationsAborted = FALSE; fileop.lpszProgressTitle = NULL; fileop.hNameMappings = NULL; int ret = SHFileOperationW(&fileop); delete [] pszFrom; return (ret == 0); }
UINT DownloadAndInstallMCF(UpdateForm* temp) { UMcfEx *updateMcf = new UMcfEx(); updateMcf->onProgressEvent += delegate(temp, &UpdateForm::onProgressN); updateMcf->onDownloadProgressEvent += delegate(temp, &UpdateForm::onProgressD); DeleteFile(UPDATEXML); std::wstring path = UTIL::OS::getAppDataPath(L"dumps\0\0"); SHFILEOPSTRUCTW lpFileOp; lpFileOp.wFunc = FO_DELETE; lpFileOp.pFrom = path.c_str(); lpFileOp.pTo = NULL; lpFileOp.hwnd = NULL; lpFileOp.fFlags = (FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR); SHFileOperationW(&lpFileOp); #ifndef DEBUG temp->getProgressControl()->setMode(MODE_DOWNLOADING); try { updateMcf->getUpdateInfo(true); } catch (gcException &e) { return DispUpdateError(temp, e); } catch (...) { ::MessageBox(temp->GetSafeHwnd(), "Failed to get update info.", "Desura: ERROR", MB_OK); return 1; } if (!updateMcf->checkMcf()) { char msg[255]; Safe::snprintf(msg, 255, "Failed to update Desura: %s", updateMcf->getLastError()); ::MessageBox(temp->GetSafeHwnd(), msg, "Desura: ERROR", MB_OK); exit(-3); return 1; } try { updateMcf->setFile(UPDATEFILE_W); updateMcf->downloadMcf(); temp->getProgressControl()->setMode(MODE_INSTALLING); updateMcf->install(L".\\"); } catch (gcException &e) { return DispUpdateError(temp, e); } #ifndef DEBUG try { updateMcf->setRegValues(); } catch (gcException &e) { return DispUpdateError(temp, e); } #endif updateMcf->deleteMcf(); safe_delete(updateMcf); #else updateMcf->setFile(UPDATEFILE_W); updateMcf->parseMCF(); updateMcf->install(L".\\test\\"); #endif return 0; }
bool DkUtils::moveToTrash(const QString& filePath) { QFileInfo fileInfo(filePath); if (!fileInfo.exists()) { qDebug() << "Sorry, I cannot delete a non-existing file: " << filePath; return false; } // code is based on:http://stackoverflow.com/questions/17964439/move-files-to-trash-recycle-bin-in-qt #ifdef Q_OS_WIN std::wstring winPath = (fileInfo.isSymLink()) ? qStringToStdWString(fileInfo.symLinkTarget()) : qStringToStdWString(filePath); winPath.append(1, L'\0'); // path string must be double nul-terminated SHFILEOPSTRUCTW shfos = {}; shfos.hwnd = nullptr; // handle to window that will own generated windows, if applicable shfos.wFunc = FO_DELETE; shfos.pFrom = winPath.c_str(); shfos.pTo = nullptr; // not used for deletion operations shfos.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; // use the recycle bin const int retVal = SHFileOperationW(&shfos); return retVal == 0; // true if no error code //#elif Q_OS_LINUX // bool TrashInitialized = false; // QString TrashPath; // QString TrashPathInfo; // QString TrashPathFiles; // // if( !TrashInitialized ) { // QStringList paths; // const char* xdg_data_home = getenv( "XDG_DATA_HOME" ); // if( xdg_data_home ){ // qDebug() << "XDG_DATA_HOME not yet tested"; // QString xdgTrash( xdg_data_home ); // paths.append( xdgTrash + "/Trash" ); // } // QString home = QStandardPaths::writableLocation( QStandardPaths::HomeLocation ); // paths.append( home + "/.local/share/Trash" ); // paths.append( home + "/.trash" ); // foreach( QString path, paths ){ // if( TrashPath.isEmpty() ){ // QDir dir( path ); // if( dir.exists() ){ // TrashPath = path; // } // } // } // if (TrashPath.isEmpty()) // return false; // TrashPathInfo = TrashPath + "/info"; // TrashPathFiles = TrashPath + "/files"; // if (!QDir(TrashPathInfo).exists() || !QDir(TrashPathFiles).exists()) // return false; // TrashInitialized = true; // } // // QString info; // info += "[Trash Info]\nPath="; // info += filePath; // info += "\nDeletionDate="; // info += QDateTime::currentDateTime().toString("yyyy-MM-ddThh:mm:ss.zzzZ"); // info += "\n"; // QString trashname = fileInfo.fileName(); // QString infopath = TrashPathInfo + "/" + trashname + ".trashinfo"; // QString trashPath = TrashPathFiles + "/" + trashname; // int nr = 1; // while( QFileInfo( infopath ).exists() || QFileInfo( trashPath ).exists() ){ // nr++; // trashname = fileInfo.baseName() + "." + QString::number( nr ); // if( !fileInfo.completeSuffix().isEmpty() ){ // trashname += QString( "." ) + fileInfo.completeSuffix(); // } // infopath = TrashPathInfo + "/" + trashname + ".trashinfo"; // trashPath = TrashPathFiles + "/" + trashname; // } // QDir dir; // if( !dir.rename( filePath, trashPath )) { // return false; // } // File infofile; // infofile.createUtf8( infopath, info ); // return true; #else QFile fileHandle(filePath); return fileHandle.remove(); #endif return false; // should never be hit }
static HRESULT WINAPI ISF_Desktop_ISFHelper_fnDeleteItems (ISFHelper * iface, UINT cidl, LPCITEMIDLIST * apidl) { IGenericSFImpl *This = impl_from_ISFHelper(iface); UINT i; SHFILEOPSTRUCTW op; WCHAR wszPath[MAX_PATH]; WCHAR wszCaption[50]; WCHAR *wszPathsList; HRESULT ret; WCHAR *wszCurrentPath; UINT bRestoreWithDeskCpl = FALSE; int res; TRACE ("(%p)(%u %p)\n", This, cidl, apidl); if (cidl==0) return S_OK; for(i = 0; i < cidl; i++) { if (_ILIsMyComputer(apidl[i])) bRestoreWithDeskCpl++; else if (_ILIsNetHood(apidl[i])) bRestoreWithDeskCpl++; else if (_ILIsMyDocuments(apidl[i])) bRestoreWithDeskCpl++; } if (bRestoreWithDeskCpl) { /* FIXME use FormatMessage * use a similar message resource as in windows */ LoadStringW(shell32_hInstance, IDS_DELETEMULTIPLE_TEXT, wszPath, sizeof(wszPath)/sizeof(WCHAR)); wszPath[(sizeof(wszPath)/sizeof(WCHAR))-1] = 0; LoadStringW(shell32_hInstance, IDS_DELETEITEM_CAPTION, wszCaption, sizeof(wszCaption)/sizeof(WCHAR)); wszCaption[(sizeof(wszCaption)/sizeof(WCHAR))-1] = 0; res = SHELL_ConfirmMsgBox(GetActiveWindow(), wszPath, wszCaption, NULL, cidl > 1); if (res == IDD_YESTOALL || res == IDYES) { for(i = 0; i < cidl; i++) { if (_ILIsMyComputer(apidl[i])) SetNamespaceExtensionVisibleStatus(L"{20D04FE0-3AEA-1069-A2D8-08002B30309D}", 0x1); else if (_ILIsNetHood(apidl[i])) SetNamespaceExtensionVisibleStatus(L"{208D2C60-3AEA-1069-A2D7-08002B30309D}", 0x1); else if (_ILIsMyDocuments(apidl[i])) SetNamespaceExtensionVisibleStatus(L"{450D8FBA-AD25-11D0-98A8-0800361B1103}", 0x1); } } } if (This->sPathTarget) lstrcpynW(wszPath, This->sPathTarget, MAX_PATH); else wszPath[0] = '\0'; PathAddBackslashW(wszPath); wszPathsList = build_paths_list(wszPath, cidl, apidl); ZeroMemory(&op, sizeof(op)); op.hwnd = GetActiveWindow(); op.wFunc = FO_DELETE; op.pFrom = wszPathsList; op.fFlags = FOF_ALLOWUNDO; if (SHFileOperationW(&op)) { WARN("SHFileOperation failed\n"); ret = E_FAIL; } else ret = S_OK; /* we currently need to manually send the notifies */ wszCurrentPath = wszPathsList; for (i = 0; i < cidl; i++) { LONG wEventId; if (_ILIsFolder(apidl[i])) wEventId = SHCNE_RMDIR; else if (_ILIsValue(apidl[i])) wEventId = SHCNE_DELETE; else continue; /* check if file exists */ if (GetFileAttributesW(wszCurrentPath) == INVALID_FILE_ATTRIBUTES) { LPITEMIDLIST pidl = ILCombine(This->pidlRoot, apidl[i]); SHChangeNotify(wEventId, SHCNF_IDLIST, pidl, NULL); SHFree(pidl); } wszCurrentPath += wcslen(wszCurrentPath)+1; } HeapFree(GetProcessHeap(), 0, wszPathsList); return ret; }
BOOL slimhelper::RecyclePath(const CString& strFilePath, BOOL bKeepRootDir) { BOOL retval = FALSE; CString strOldSecurityDescriptor; HRESULT hr; int nRetCode; ULARGE_INTEGER tempSize; DWORD dwFileAttributes; BOOL bIsDir = FALSE; SHFILEOPSTRUCTW fileopt = { 0 }; ULONGLONG qwFileSize = 0; TCHAR* szDelPath = new TCHAR[MAX_PATH * 2]; CString strFlagFile; RtlZeroMemory(szDelPath, sizeof(TCHAR) * MAX_PATH * 2); StringCchCopy(szDelPath, MAX_PATH * 2, strFilePath); fileopt.pFrom = szDelPath; fileopt.wFunc = FO_DELETE; fileopt.fFlags = FOF_SILENT|FOF_NOCONFIRMATION|FOF_NOERRORUI|FOF_ALLOWUNDO; dwFileAttributes = ::GetFileAttributes(strFilePath); if (INVALID_FILE_ATTRIBUTES == dwFileAttributes) goto clean0; if (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) bIsDir = TRUE; GrantFileAccess(strFilePath, strOldSecurityDescriptor, bIsDir); //if (!GrantFileAccess(strFilePath, strOldSecurityDescriptor)) // goto clean0; strFlagFile = strFilePath + _T("\\"); strFlagFile += g_kSlimFlag; if (bIsDir) { ::DeleteFile(strFlagFile); nRetCode = SHFileOperationW(&fileopt); if (32 == nRetCode) goto clean0; if (0x78 == nRetCode || 5 == nRetCode) { GrantDirAccess(strFilePath); ::DeleteFile(strFlagFile); nRetCode = SHFileOperationW(&fileopt);; } if (!nRetCode) { if (bKeepRootDir) { ::CreateDirectory(strFilePath, NULL); // 创建瘦身后的标记文件 // CAtlFile file; // file.Create(strFlagFile, // FILE_GENERIC_WRITE, // FILE_SHARE_READ|FILE_SHARE_WRITE, // CREATE_ALWAYS); } retval = TRUE; } goto clean0; } if (dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED || dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE) { tempSize.LowPart = GetCompressedFileSize(strFilePath, &tempSize.HighPart); qwFileSize = tempSize.QuadPart; } else { CAtlFile file; hr = file.Create(strFilePath, FILE_GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, OPEN_EXISTING); if (FAILED(hr)) goto clean0; tempSize.LowPart = GetFileSize((HANDLE)file, &tempSize.HighPart); qwFileSize = tempSize.QuadPart; } qwFileSize = FileSizeConver::Instance().FileSizeOnDisk(qwFileSize); nRetCode = SHFileOperationW(&fileopt); if (nRetCode) goto clean0; retval = TRUE; clean0: if (szDelPath) { delete[] szDelPath; szDelPath = NULL; } return retval; }
static void on_theme_install(HWND dialog) { static const WCHAR filterMask[] = {0,'*','.','m','s','s','t','y','l','e','s',';', '*','.','t','h','e','m','e',0,0}; static const WCHAR themeExt[] = {'.','T','h','e','m','e',0}; const int filterMaskLen = sizeof(filterMask)/sizeof(filterMask[0]); OPENFILENAMEW ofn; WCHAR filetitle[MAX_PATH]; WCHAR file[MAX_PATH]; WCHAR filter[100]; WCHAR title[100]; LoadStringW (GetModuleHandleW(NULL), IDS_THEMEFILE, filter, sizeof (filter) / sizeof (filter[0]) - filterMaskLen); memcpy (filter + lstrlenW (filter), filterMask, filterMaskLen * sizeof (WCHAR)); LoadStringW (GetModuleHandleW(NULL), IDS_THEMEFILE_SELECT, title, sizeof (title) / sizeof (title[0])); ofn.lStructSize = sizeof(OPENFILENAMEW); ofn.hwndOwner = dialog; ofn.hInstance = 0; ofn.lpstrFilter = filter; ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0; ofn.nFilterIndex = 0; ofn.lpstrFile = file; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof(file)/sizeof(filetitle[0]); ofn.lpstrFileTitle = filetitle; ofn.lpstrFileTitle[0] = '\0'; ofn.nMaxFileTitle = sizeof(filetitle)/sizeof(filetitle[0]); ofn.lpstrInitialDir = NULL; ofn.lpstrTitle = title; ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_ENABLESIZING; ofn.nFileOffset = 0; ofn.nFileExtension = 0; ofn.lpstrDefExt = NULL; ofn.lCustData = 0; ofn.lpfnHook = NULL; ofn.lpTemplateName = NULL; if (GetOpenFileNameW(&ofn)) { static const WCHAR themesSubdir[] = { '\\','T','h','e','m','e','s',0 }; static const WCHAR backslash[] = { '\\',0 }; WCHAR themeFilePath[MAX_PATH]; SHFILEOPSTRUCTW shfop; if (FAILED (SHGetFolderPathW (NULL, CSIDL_RESOURCES|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, themeFilePath))) return; if (lstrcmpiW(PathFindExtensionW(filetitle), themeExt)==0) { do_parse_theme(file); SendMessageW(GetParent(dialog), PSM_CHANGED, 0, 0); return; } PathRemoveExtensionW (filetitle); /* Construct path into which the theme file goes */ lstrcatW (themeFilePath, themesSubdir); lstrcatW (themeFilePath, backslash); lstrcatW (themeFilePath, filetitle); /* Create the directory */ SHCreateDirectoryExW (dialog, themeFilePath, NULL); /* Append theme file name itself */ lstrcatW (themeFilePath, backslash); lstrcatW (themeFilePath, PathFindFileNameW (file)); /* SHFileOperation() takes lists as input, so double-nullterminate */ themeFilePath[lstrlenW (themeFilePath)+1] = 0; file[lstrlenW (file)+1] = 0; /* Do the copying */ WINE_TRACE("copying: %s -> %s\n", wine_dbgstr_w (file), wine_dbgstr_w (themeFilePath)); shfop.hwnd = dialog; shfop.wFunc = FO_COPY; shfop.pFrom = file; shfop.pTo = themeFilePath; shfop.fFlags = FOF_NOCONFIRMMKDIR; if (SHFileOperationW (&shfop) == 0) { scan_theme_files(); if (!fill_theme_list (GetDlgItem (dialog, IDC_THEME_THEMECOMBO), GetDlgItem (dialog, IDC_THEME_COLORCOMBO), GetDlgItem (dialog, IDC_THEME_SIZECOMBO))) { SendMessageW (GetDlgItem (dialog, IDC_THEME_COLORCOMBO), CB_SETCURSEL, -1, 0); SendMessageW (GetDlgItem (dialog, IDC_THEME_SIZECOMBO), CB_SETCURSEL, -1, 0); enable_size_and_color_controls (dialog, FALSE); } else { enable_size_and_color_controls (dialog, TRUE); } } else WINE_TRACE("copy operation failed\n"); } else WINE_TRACE("user cancelled\n"); }
static int op_removesl(ops_t *ops, void *data, const char *src, const char *dst) { if(cfg.delete_prg[0] != '\0') { #ifndef _WIN32 char *escaped; char cmd[2*PATH_MAX + 1]; const int cancellable = (data == NULL); escaped = shell_like_escape(src, 0); if(escaped == NULL) { return -1; } snprintf(cmd, sizeof(cmd), "%s %s", cfg.delete_prg, escaped); free(escaped); LOG_INFO_MSG("Running trash command: \"%s\"", cmd); return background_and_wait_for_errors(cmd, cancellable); #else char cmd[PATH_MAX*2 + 1]; snprintf(cmd, sizeof(cmd), "%s \"%s\"", cfg.delete_prg, src); to_back_slash(cmd); return os_system(cmd); #endif } if(!cfg.use_system_calls) { #ifndef _WIN32 char *escaped; char cmd[16 + PATH_MAX]; int result; const int cancellable = data == NULL; escaped = shell_like_escape(src, 0); if(escaped == NULL) return -1; snprintf(cmd, sizeof(cmd), "rm -rf %s", escaped); LOG_INFO_MSG("Running rm command: \"%s\"", cmd); result = background_and_wait_for_errors(cmd, cancellable); free(escaped); return result; #else if(is_dir(src)) { char path[PATH_MAX]; int err; copy_str(path, sizeof(path), src); to_back_slash(path); wchar_t *const utf16_path = utf8_to_utf16(path); SHFILEOPSTRUCTW fo = { .hwnd = NULL, .wFunc = FO_DELETE, .pFrom = utf16_path, .pTo = NULL, .fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI, }; err = SHFileOperationW(&fo); log_msg("Error: %d", err); free(utf16_path); return err; } else { int ok; wchar_t *const utf16_path = utf8_to_utf16(src); DWORD attributes = GetFileAttributesW(utf16_path); if(attributes & FILE_ATTRIBUTE_READONLY) { SetFileAttributesW(utf16_path, attributes & ~FILE_ATTRIBUTE_READONLY); } ok = DeleteFileW(utf16_path); if(!ok) { LOG_WERROR(GetLastError()); } free(utf16_path); return !ok; } #endif }
static int op_removesl(ops_t *ops, void *data, const char *src, const char *dst) { const char *const delete_prg = (ops == NULL) ? cfg.delete_prg : ops->delete_prg; if(delete_prg[0] != '\0') { #ifndef _WIN32 char *escaped; char cmd[2*PATH_MAX + 1]; const int cancellable = (data == NULL); escaped = shell_like_escape(src, 0); if(escaped == NULL) { return -1; } snprintf(cmd, sizeof(cmd), "%s %s", delete_prg, escaped); free(escaped); LOG_INFO_MSG("Running trash command: \"%s\"", cmd); return run_operation_command(ops, cmd, cancellable); #else char cmd[PATH_MAX*2 + 1]; snprintf(cmd, sizeof(cmd), "%s \"%s\"", delete_prg, src); to_back_slash(cmd); return os_system(cmd); #endif } if(!ops_uses_syscalls(ops)) { #ifndef _WIN32 char *escaped; char cmd[16 + PATH_MAX]; int result; const int cancellable = data == NULL; escaped = shell_like_escape(src, 0); if(escaped == NULL) return -1; snprintf(cmd, sizeof(cmd), "rm -rf %s", escaped); LOG_INFO_MSG("Running rm command: \"%s\"", cmd); result = run_operation_command(ops, cmd, cancellable); free(escaped); return result; #else if(is_dir(src)) { char path[PATH_MAX]; int err; copy_str(path, sizeof(path), src); to_back_slash(path); wchar_t *utf16_path = utf8_to_utf16(path); /* SHFileOperationW requires pFrom to be double-nul terminated. */ const size_t len = wcslen(utf16_path); utf16_path = reallocarray(utf16_path, len + 1U + 1U, sizeof(*utf16_path)); utf16_path[len + 1U] = L'\0'; SHFILEOPSTRUCTW fo = { .hwnd = NULL, .wFunc = FO_DELETE, .pFrom = utf16_path, .pTo = NULL, .fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI, }; err = SHFileOperationW(&fo); log_msg("Error: %d", err); free(utf16_path); return err; } else { int ok; wchar_t *const utf16_path = utf8_to_utf16(src); DWORD attributes = GetFileAttributesW(utf16_path); if(attributes & FILE_ATTRIBUTE_READONLY) { SetFileAttributesW(utf16_path, attributes & ~FILE_ATTRIBUTE_READONLY); } ok = DeleteFileW(utf16_path); if(!ok) { LOG_WERROR(GetLastError()); } free(utf16_path); return !ok; } #endif }
static HRESULT WINAPI ISF_Desktop_ISFHelper_fnCopyItems (ISFHelper * iface, IShellFolder * pSFFrom, UINT cidl, LPCITEMIDLIST * apidl) { IPersistFolder2 *ppf2 = NULL; WCHAR szSrcPath[MAX_PATH]; WCHAR szTargetPath[MAX_PATH]; SHFILEOPSTRUCTW op; LPITEMIDLIST pidl; LPWSTR pszSrc, pszTarget, pszSrcList, pszTargetList, pszFileName; int res, length; STRRET strRet; IGenericSFImpl *This = impl_from_ISFHelper(iface); TRACE ("(%p)->(%p,%u,%p)\n", This, pSFFrom, cidl, apidl); IShellFolder_QueryInterface (pSFFrom, &IID_IPersistFolder2, (LPVOID *) & ppf2); if (ppf2) { if (FAILED(IPersistFolder2_GetCurFolder (ppf2, &pidl))) { IPersistFolder2_Release(ppf2); return E_FAIL; } IPersistFolder2_Release(ppf2); if (FAILED(IShellFolder_GetDisplayNameOf(pSFFrom, pidl, SHGDN_FORPARSING, &strRet))) { SHFree (pidl); return E_FAIL; } if (FAILED(StrRetToBufW(&strRet, pidl, szSrcPath, MAX_PATH))) { SHFree (pidl); return E_FAIL; } SHFree (pidl); pszSrc = PathAddBackslashW (szSrcPath); wcscpy(szTargetPath, This->sPathTarget); pszTarget = PathAddBackslashW (szTargetPath); pszSrcList = build_paths_list(szSrcPath, cidl, apidl); pszTargetList = build_paths_list(szTargetPath, cidl, apidl); if (!pszSrcList || !pszTargetList) { if (pszSrcList) HeapFree(GetProcessHeap(), 0, pszSrcList); if (pszTargetList) HeapFree(GetProcessHeap(), 0, pszTargetList); SHFree (pidl); IPersistFolder2_Release (ppf2); return E_OUTOFMEMORY; } ZeroMemory(&op, sizeof(op)); if (!pszSrcList[0]) { /* remove trailing backslash */ pszSrc--; pszSrc[0] = L'\0'; op.pFrom = szSrcPath; } else { op.pFrom = pszSrcList; } if (!pszTargetList[0]) { /* remove trailing backslash */ if (pszTarget - szTargetPath > 3) { pszTarget--; pszTarget[0] = L'\0'; } else { pszTarget[1] = L'\0'; } op.pTo = szTargetPath; } else { op.pTo = pszTargetList; } op.hwnd = GetActiveWindow(); op.wFunc = FO_COPY; op.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMMKDIR; res = SHFileOperationW(&op); if (res == DE_SAMEFILE) { length = wcslen(szTargetPath); pszFileName = wcsrchr(pszSrcList, '\\'); pszFileName++; if (LoadStringW(shell32_hInstance, IDS_COPY_OF, pszTarget, MAX_PATH - length)) { wcscat(szTargetPath, L" "); } wcscat(szTargetPath, pszFileName); op.pTo = szTargetPath; res = SHFileOperationW(&op); } HeapFree(GetProcessHeap(), 0, pszSrcList); HeapFree(GetProcessHeap(), 0, pszTargetList); if (res) return E_FAIL; else return S_OK; } return E_FAIL; }