Delphi provides many functions for file operations, including directory creation and deletion, setting the current directory, getting the current directory, etc. Directory deletion includes function (Function) RemoveDir and procedure (PRocedure) RmDir, but they can only delete empty directories, and cannot delete non-empty directories. To delete the entire directory tree (DelTree), you must write a program to delete the subdirectories and files in it.
Files in the directory can be deleted by calling the function DeleteFile, but special files (read-only, system, hidden, etc.) cannot be effectively deleted. The file attributes must be changed to ordinary files before they can be deleted. You can use the function FileSetAttr to change file attributes. Here, the attributes of the special file are set to ordinary file attributes (the attribute value is 0).
Considering that the tree directory structure is most suitable for recursive methods, recursive algorithms are used here to implement the DelTree function. The following is the specific implementation procedure.
//path is the directory path to be deleted
//Returns True if the directory is successfully deleted, otherwise returns False
function TForm1.Deltree (path : string): Boolean;
var
SearchRec: TSearchRec;
begin
//Determine whether the directory exists
if DirectoryExists(path) then
begin
//Enter the directory and delete the subdirectories and files in it
oldDir := GetCurrentDir;
ChDir(path);
//Find all files in the directory
FindFirst(′??.??′, faAnyFile, SearchRec);
repeat
//Modify file attributes to normal attribute values
FileSetAttr(SearchRec.Name,0);
//If it is a directory and not . and .., call DelTree recursively
if(SearchRec.Attr and faDirectory > 0) then
begin
if(SearchRec.Name[1]<>′.′) then
if(not Deltree(SearchRec.Name)) then
break;
end
//If it is a file, delete it directly
else
if(not DeleteFile(SearchRec.Name))then
break ;
//Continue searching until the end
until (FindNext(SearchRec)<>0) ;
//Go back to the parent directory and delete the directory
ChDir(′..′);
Result := ReMoveDir(path);
SetCurrentDir(oldDir);
end
else
Result := False ;
end ;
This program is compiled and passed under Windows 98 and Delphi 4.0.