delphi3000.com - the free delphi knowledge platform
delphi3000.com - the free delphi knowledge platform
492 Users Online NOW
Have a look at your member-status

connecting people's knowledge


  - Recent ArticlesRSS feed for Recent Articles on delphi3000.com
  - List of All Articles
  - Top Viewed Articles
  - Articles (+Attachem.)
  - Articles Of Interest
  - Categories
  - Top Uploader
  - Search
  - Index

  - My Home
  - Submit an Article
  - My Articles
  - My Personal Data
  - My Bookmarks
  - Activities
  - Login/Logout

  - Sign Up
  - Why Sign Up
  - Newsletter

  - Press
  - Advertise

  - Contact
  - Feedback





Community
Borland
ClubeDelphi
Dr. Bob
UK-BUG
Delphi Meetings
Planeta Delphi



Loremo - the 1.5 liter car coming in 2009




Startblatt.de






Share this article with friendsShare this article with friends
Rate this articleRate this article - to keep the quality of delphi3000.com !
Comment this article or read through previous comments (10)


Folder Copy By RecursionGo to Danielle Sherstobitoff's websiteFormat this article printer-friendly!Bookmark function is only available for registered users!
Product:
Delphi all versions
Category:
Files Operation
Skill Level:
Scoring:
Last Update:
10/23/2000
Search Keys:
delphi delphi3000 article borland vcl code-snippet folder directory copy recursion copyfile mkdir $I- $I+ FindFirst Find-First FindNext Find-Next
Times Scored:
8
Visits:
6677
Uploader: Danielle Sherstobitoff
Company: Exan WinVet Software Inc
Reference: N/A
 
Question/Problem/Abstract:
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





Please rate this article!
Skill level:
BeginnerExpert

Useful:
No!Very!

Overall rating:
PoorExcellent



Comments to this article
Write a new comment
Copy Folder
    Anjali (Nov 18 2005 7:58PM)

I am trying to implement this code:
procedure CopyFolder(SrcFolder, DstFolder : String);
var
  SearchRec : TSearchRec;
  Src, Dst     : String;

begin
  Src := IncludeTrailingBackslash(SrcFolder);
  Dst := IncludeTrailingBackslash(DstFolder);
  ForceDirectories(Dst);

  if FindFirst(Src + '*.*', faAnyFile, SearchRec) = 0 then
    try
      repeat
        with SearchRec do
          if (Name <> '.') and (Name <> '..') then
            if (Attr and faDirectory) > 0 then
              CopyFolder(Src + Name, Dst + Name)
            else
              CopyFile(Pchar(Src + Name), PChar(Dst + Name), True);
      until FindNext(SearchRec) <> 0;
    finally
      FindClose(SearchRec);
    end ;
end;

I am getting a compilation error - Incompatible types: 'Cardinal' and 'TSearchRec' at FindClose(SearchRec).
How do i resolve this?
Respond

Thanks!
    Bryan Cairns (Sep 7 2001 7:02PM)

I am new to Delphi - thanks you saved me from pulling out what little hair I have left.
Respond

Its good that so many people are commenting
    Danielle Sherstobitoff (Oct 26 2000 10:38AM)

Thank you all for your comment on my article.  I'm so glad that people are coming out of the woodwork to discuss this.

Like so many people out there... I'm not a walking encyclopedia of Delphi commands and API calls.  I have a background in pascal and c++ and wanted to help people out.  

If you are going to make further comments please include source code as examples of what you are saying.

Thanks,
  Danielle.
Respond

implemantatio of SHfileoperation
    CRA (Oct 26 2000 8:34AM)

procedure FolderAction(fromDir,toDir:string);
var SHFileOp:TSHFileOpStruct;
begin
SHFileOp.wnd   :=form1.handle;
SHFileOp.wFunc :=FO_MOVE;
SHFileOp.pFrom :=Pchar(fromDir  +#0+#0);
SHFileOp.pTo   :=Pchar(toDir    +#0+#0);
SHFileOp.fFlags:=FOF_SILENT or FOF_NOCONFIRMATION;
SHFileOp.fAnyOperationsAborted:=false;
SHFileOp.hNameMappings        :=NIL;
SHFileOp.lpszProgressTitle    :=NIL;
SHFileOperation(SHFileOp);
end;
Respond

RE: implemantatio of SHfileoperation
Feroz Zahid (Jun 25 2004 8:17PM)

You should do it without SHFileOperation. Use CopyFile FindFirstFile FindNextFile APIs to do the work.
Respond

a improvement for simplicity
    Xianguang Li (Oct 26 2000 1:03AM)

the routine can be simplified as the following:

procedure CopyFolder(src, dest: string);
var
  sts: Integer;
  SR: TSearchRec;
begin
  sts := FindFirst(src + '*.*', faAnyFile, SR);
  while sts = 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;
    sts := FindNext(SR);
  end;
  FindClose(SR);
end;

There is also problem. Because some directory names may contain
'.' and some files haven't postfix. We can't distinguish file and directory
by having '.' or not. Sorry, I don't know how to do this. May be some one
can help us to make this routine robust!
Respond

there is...
    CRA (Oct 25 2000 2:10AM)

a API function called SHfileOperation which does all this work for you.

greetings
CRA
Respond

CopyFolder
    Thinus Barnard (Oct 24 2000 9:41AM)

Here is a more streamlined example, essentially the same logic. It can be enhanced to deal with errors that can occur during ForceDirectories and CopyFile, read the return value of those functions to determine whether they succeeded or not.

procedure CopyFolder(SrcFolder, DstFolder : String);
var
  SearchRec : TSearchRec;
  Src, Dst     : String;

begin
  Src := IncludeTrailingBackslash(SrcFolder);
  Dst := IncludeTrailingBackslash(DstFolder);
  ForceDirectories(Dst);

  if FindFirst(Src + '*.*', faAnyFile, SearchRec) = 0 then
    try
      repeat
        with SearchRec do
          if (Name <> '.') and (Name <> '..') then
            if (Attr and faDirectory) > 0 then
              CopyFolder(Src + Name, Dst + Name)
            else
              CopyFile(Pchar(Src + Name), PChar(Dst + Name), True);
      until FindNext(SearchRec) <> 0;
    finally
      FindClose(SearchRec);
    end ;
end;

Respond

RE: CopyFolder
Pedro MG (Dec 26 2001 8:41PM)

Great,

works very well.
Nice code !
Regards,
Pedro MG
Respond

RE: CopyFolder
Anjali (Nov 18 2005 7:56PM)

I am trying to implement this code to CopyFolders.. but i get a compilation error at FindClose(SearchRec); - incompatible types: 'Cardinal' and 'TSearchRect'. How do i resolve this?
Respond














 
Sign up to consume product discounts for Bronze memberships !

read more


  Visit our Sponsor

 

  Community Ad of
Peganza
 
   














 







     
  Copyright © 2000 - 2007 delphi3000.com - All rights reserved. Terms of use. || Privacy
delphi3000.com is a service by bluestep.com IT-Services GmbH (Vienna)