Mega Code Archive

 
Categories / Delphi / Files
 

File Operations the 32 bit way

Title: File Operations the 32-bit way Question: This article shows how to use the SHFileOperation to get dirty file work done the easy way. The SHFileOperation is a function supplied by Windows 95/98/NT4/2000/ME to get most jobs fast done. Answer: The DoFileWork procedure shown below, will help you to get most basic file work done by using the Win32 Shell API function: SHFileOperation. The syntax of the function is: function DoFileWork(aWnd: HWND; aOperation: UINT; aFrom, aTo: array of string; aFlags: FILEOP_FLAGS): Integer; The following example could be one way of calling: DoFileWork(Self.Handle, FO_DELETE, strlFiles, nil, FOF_ALLOWUNDO); This would move all files in the String List strlFiles to the trash can. Parameters: aWnd - Handle of the calling Window (Form) aOperation - anyone of the following FO_MOVE FO_COPY FO_DELETE FO_RENAME (Works on one file at a time, only) aFrom - List of the files that are to be worked on (fully qualifed file names!) aTo - List of the new file names (must be nil for FO_DELETE) aFlags - a combination among the following FOF_ALLOWUNDO - Preserve undo information FOF_FILESONLY - Do not apply to directories FOF_MULTIDESTFILES - aTo specifies a file for every file in the aFrom list FOF_NOCONFIRMATION - User is not asked to press the yes button FOF_NOERRORUI - Do not display error messages FOF_NORECURSION - Do not parse sub-folders FOF_RENAMEONCOLLISION - Create a new file name if one with same exists already FOF_SILENT - Do not display a progress dialog There are more flags, however, these are the most important ones. Result: - 0 on success - nonzero if error occured NOTE: you must include the ShellAPI unit in your uses clause! function DoFileWork( aWnd: HWND; aOperation: UINT; aFrom, aTo: TStrings; aFlags: FILEOP_FLAGS ): Integer; var I: Integer; FromPath, ToPath: string; SHFileOpStruct: TSHFileOpStruct; begin FromPath := ''; for I := 0 to aFrom.Count - 1 do FromPath := FromPath + aFrom.Strings[I] + #0; FromPath := FromPath + #0; if Assigned(aTo) then begin ToPath := ''; for I := 0 to aTo.Count - 1 do ToPath := ToPath + aTo.Strings[I] + #0; ToPath := ToPath + #0; end; with SHFileOpStruct do begin Wnd := aWnd; wFunc := aOperation; pFrom := PChar(FromPath); if Assigned(aTo) then begin pTo := PChar(ToPath) end else begin // target available pTo := nil; end; // target not available fFlags := aFlags; end; // structure Result := SHFileOperation(SHFileOpStruct); end;