Copying a large number of files in Delphi

In my application, I need to copy over 1000 small files

Here is the code I use, but it is VERY SLOW Is there a better way to do this?

procedure Tdatafeeds.RestotreTodaysFiles; var SearchRec: TSearchRec; FromFn, ToFn: string; Begin if DirectoryExists(BackupPath1) then begin try if FindFirst(BackupPath1 + '\*.*', (faAnyFile AND NOT(faDirectory)), SearchRec) = 0 then begin repeat FromFn := BackupPath1 + '\' + SearchRec.name; ToFn := DatafeedsPath1 + '\' + SearchRec.name; CopyFile(Pchar(FromFn), Pchar(ToFn), false); until FindNext(SearchRec) <> 0; end; finally FindClose(SearchRec); end; end; End; 
+6
delphi delphi-2010
source share
4 answers

Definitely go with SHFileOperation () , as suggested above, CopyFile is too slow for many files. It looks like you are basically restoring the entire folder, so the search function may be unnecessary and slow down. Something like this might help:

 uses ShellApi; function CopyDir(const fromDir, toDir: string): Boolean; var fos: TSHFileOpStruct; begin ZeroMemory(@fos, SizeOf(fos)); with fos do begin wFunc := FO_COPY; fFlags := FOF_FILESONLY; pFrom := PChar(fromDir + #0); pTo := PChar(toDir) end; Result := (0 = ShFileOperation(fos)); end; 

This function will raise a request to overwrite existing files (perhaps it can be changed to skip this), but the user can select "All", so a one-click procedure, much faster, has a progress bar and can be canceled if necessary.

+10
source share

You can use the SHFileOperation() API call and use a wildcard in the structure file name. Thus, one call will be used to copy all files at once. There is even the ability to show progress (via the callback function) and allow the user to cancel the operation.

+7
source share

I can’t check your code right now, but check this fixed version

  // (!) faAnyFile-faDirectory <--- this is wrong // we don't subtract flag values because the value will be meaningless if FindFirst(BackupPath1 + '\*.*', faAnyFile, SearchRec) = 0 then begin repeat if not (SearchRec.Attr and faDirectory) And SearchRec.Name <> "." And SearchRec.Name <> ".." Then Begin FromFn := BackupPath1 + '\' + SearchRec.name; ToFn := DatafeedsPath1 + '\' + SearchRec.name; CopyFile(Pchar(FromFn), Pchar(ToFn), false); End; until FindNext(SearchRec) <> 0; FindClose(SearchRec); end; 
+2
source share

Perhaps you can experiment with reading a bunch of files into memory and then write them to disk immediately (for example, XCOPY). It might be better on the file system.

0
source share

All Articles