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