Implement copy, delete, and move of directory in Delphi

Source: Internet
Author: User

The author in the work encountered the need to copy, delete and move the directory needs, Delphi itself provides some directory operation functions, but only for the empty directory, the directory with subdirectories, but also powerless.

Using the Win32 API function and structure, and the recursive program design idea, the author realizes the function of copying, deleting and moving any directory (equivalent to the Xcopy, deltree and move commands in DOS respectively). The implementation code is given below:

1. Copy Catalogue

In order to be able to copy a subdirectory under the directory, first define an auxiliary copy function, which is recursively executed until all the files and subdirectories in the directory are copied.

1.1 Recursive auxiliary functions for copy directory: Docopydir

function Docopydir (sdirname:string;
stodirname:string): Boolean;
Var
hfindfile:cardinal;
t,tfile:string;
SCURDIR:STRING[255];
Findfiledata:win32_find_data;
Begin
Save the current directory first
Scurdir:=getcurrentdir;
ChDir (Sdirname);
Hfindfile:=findfirstfile (' *.* ', findfiledata);
If hfindfile< >invalid_handle_value Then
Begin
If not directoryexists (Stodirname) Then
Forcedirectories (Stodirname);
Repeat
Tfile:=findfiledata.cfilename;
if (tfile= '. ') or (tfile= ' ... ') then
Continue;
If findfiledata.dwfileattributes=
File_attribute_directory Then
Begin
T:=stodirname+ ' \ ' +tfile;
If not directoryexists (t) then
Forcedirectories (t);
If Sdirname[length (sdirname)]< > ' Then
Docopydir (sdirname+ ' +tfile,t)
Else
Docopydir (Sdirname+tfile,stodirname+tfile);
End
Else
Begin
T:=stodirname+ ' \ ' +tfile;
CopyFile (Pchar (Tfile), Pchar (t), True);
End
Until FindNextFile (hfindfile,findfiledata) =false;
FindClose (hFindFile);
End
Else
Begin
ChDir (Scurdir);
Result:=false;
Exit
End
Back to the original directory
ChDir (Scurdir);
Result:=true;
End

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.