Title: Folder Copy By Recursion
Question: How do I copy the contents of one folder to another including sub folders
Answer:
I couldn't believe no one had posted this routine to a web page so I thought that I'd take care of this oversight.
Below is the code to copy file from a source folder (the contents of) to a destination folder (assuming both top folders exist)
use this code to make a missing destination topmost folder
{$I-}MkDir( path + dirname ){I+}
*See Also 'function ForceDirectories(Dir: string): Boolean;' in the Delphi Help.
uses
ShellApi; //not sure if this is required or not
procedure TForm1.CopyFolder( src, dest : string );
var
sts : Integer ;
SR: TSearchRec;
begin
sts := FindFirst( src + '*.*' , faAnyFile , SR );
if sts = 0 then
begin
if ( SR.Name '.' ) and ( SR.Name '..' ) then
begin
//Put User Feedback here if desired
Application.ProcessMessages;
if pos('.', SR.Name) = 0 then
begin
{$I-}MkDir( dest + SR.Name ) ;{$I+}
CopyFolder( src + SR.Name + '\', dest +
SR.Name + '\' ) ;
end
else
copyfile( pchar(src + SR.Name), pchar(dest + sr.name),
true );
end;
while FindNext( SR ) = 0 do
begin
if ( SR.Name '.' ) and ( SR.Name '..' ) then
begin
//Put User Feedback here if desired
Application.ProcessMessages;
if Pos('.', SR.Name) = 0 then
begin
{$I-}MkDir( dest + SR.Name );{$I+}
CopyFolder( src + SR.Name + '\', dest + SR.Name
+ '\' ) ;
end
else
copyfile( pchar(src + SR.Name), pchar(dest +
sr.name), true );
end;
end;
FindClose( SR ) ;
end ;
end;
I hope this helps someone out there save some time. I based my recursive logic on another article here at www.delphi3000.com but had to make some allowances due to changing the code from recursive delete folders to recursive copy. You can change this to a move folder function by changing copyfile to movefile.
Danielle Sherstobitoff