请教delphi删除文件夹问题(50分)

  • 主题发起人 主题发起人 zybzhen
  • 开始时间 开始时间
Z

zybzhen

Unregistered / Unconfirmed
GUEST, unregistred user!
我需要删除指定文件夹下所有文件及文件夹,如何作?
例如:
c:/abc
c:/abc/123
c:/abc/234
c:/abc/*.*
只保留c:/abc其他的都删除,而且其他的名字未知
 
你就遍历整个文件夹,找到文件就删除。
别人的代码,你可以参考。加上删除代码就好。
//判斷是不是目錄
function IsValidDir(SearchRec: TSearchRec): Boolean;
begin
result:= (SearchRec.Attr and faDirectory = faDirectory) and (SearchRec.Name <> '.') and (SearchRec.Name <> '..');
end;

//傳入一個路徑,查找這個路徑下的所有文件(也查找所有子目錄下的所有文件)
procedure SearchAllPath(Path: string);
var
i: Integer;
sl_SubDir: TStrings;
SearchRec: TSearchRec;
begin
CheckStop;
if Trim(Path) = '' then exit;
sl_SubDir:= TStringList.Create;
if (FindFirst(Path + '/*.*', faDirectory, SearchRec) = 0) then
begin
if IsValidDir(SearchRec) and cbSubDir.Checked then sl_SubDir.Add(SearchRec.Name);
while (FindNext(SearchRec) = 0) do
begin
if IsValidDir(SearchRec) and cbSubDir.Checked then sl_SubDir.Add(SearchRec.Name)
else if IsValidFile(SearchRec) then DoFile(Path, SearchRec.Name); //找到文件,進行處理
end;
end;
FindClose(SearchRec);
for i:= 0 to sl_SubDir.Count - 1 do
SearchAllPath(Path + '/' + sl_SubDir.Strings);
sl_SubDir.Free;
end;
 
//删除目录树
function DeleteDirectoryTree(Path:string):boolean;
var SearchRec:TSearchRec;
SFI:string;
begin
Result:=False;
if Path = '' then exit;
if Path[length(Path)]<>'/' then Path:=Path+'/';
SFI:=Path+'*.*';

if FindFirst(SFI,faAnyFile,SearchRec)=0 then
begin
repeat
begin
if (SearchRec.Name ='.') or (SearchRec.Name ='..') then continue;
if (SearchRec.Attr and faDirectory<>0) then
begin
if not DeleteDirectoryTree(Path+SearchRec.name) then
Result:=FALSE;
end
else
begin
FileSetAttr(Path+SearchRec.Name,128);
DeleteFile(Path+SearchRec.Name);
end;
end
until FindNext(SearchRec)<>0;
FindClose(SearchRec);
end;

FileSetAttr(Path,0);
if RemoveDir(Path) then
Result:=TRUE
else
Result:=FALSE;
end;
 
procedure DeleteFileDirectors(aHandle:THandle;sDirectory:String);
var fStruct:TSHFileOpStruct;
begin
with fStruct do
begin
Wnd:=aHandle;
wFunc:=FO_Delete;
pFrom:=pchar(sDirectory+#0#0);
fFlags:=FOF_AllowUndo;
end;
try
if ShFileOperation(fStruct)<>0 then showmessage('Delete Files Error!');
except
exit;
end;
end;
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
D
回复
0
查看
2K
DelphiTeacher的专栏
D
后退
顶部