这是我写的一个删除文件夹及其子文件夹下所有文件的程序,可参看一下 procedure DeleteDir(SourcePath: String); var sr: TSearchRec; begin // Screen.Cursor:=crHourGlass; SourcePath:=IncludeTrailingPathDelimiter(SourcePath); if FindFirst(SourcePath + '*.*', faAnyFile , sr) = 0 then begin repeat { 如果是只读或隐藏文件则先修改其属性为一般文件才能删除 } if ((SR.Attr and SysUtils.faReadOnly)<>0) or ((SR.Attr and faHidden)<> 0) then SetFileAttributes(Pchar(SourcePath + sr.Name),FILE_ATTRIBUTE_NORMAL); if (sr.Attr = faDirectory + SysUtils.faReadOnly) or (sr.Attr = faDirectory + faHidden) or ((sr.Attr = faDirectory) and (sr.Name <> '.') and (sr.Name <> '..')) then begin { 有下级子目录也一并删除 } System.ChDir(sr.Name); DeleteDir(SourcePath + sr.Name); System.ChDir('..'); end; Windows.DeleteFile(Pchar(SourcePath + sr.Name)); until FindNext(sr) <> 0; Windows.FindClose(sr.FindHandle); RemoveDir(SourcePath); end; // Screen.Cursor:=crDefault; end;
procedure TForm1.Button1Click(Sender: TObject); var ss:Tsearchrec; filepath:string; begin filepath:='c:\'; listbox1.Items.Clear; if findfirst(filepath+'*.*',faAnyFile,ss)=0 then begin if not ((ss.Attr and fadirectory)=fadirectory) then listbox1.Items.Add(ss.Name); while findnext(ss)=0 do begin if not ((ss.attr and fadirectory)=fadirectory) then listbox1.Items.Add(ss.Name);//可添加路径,如: filepath+ss.name; end; findclose(ss); end; end;
procedure DeleteDir(SourcePath: String);
var
sr: TSearchRec;
begin
// Screen.Cursor:=crHourGlass;
SourcePath:=IncludeTrailingPathDelimiter(SourcePath);
if FindFirst(SourcePath + '*.*', faAnyFile , sr) = 0 then
begin
repeat
{ 如果是只读或隐藏文件则先修改其属性为一般文件才能删除 }
if ((SR.Attr and SysUtils.faReadOnly)<>0) or ((SR.Attr and faHidden)<> 0) then SetFileAttributes(Pchar(SourcePath + sr.Name),FILE_ATTRIBUTE_NORMAL);
if (sr.Attr = faDirectory + SysUtils.faReadOnly) or (sr.Attr = faDirectory + faHidden) or ((sr.Attr = faDirectory) and (sr.Name <> '.') and (sr.Name <> '..')) then
begin
{ 有下级子目录也一并删除 }
System.ChDir(sr.Name);
DeleteDir(SourcePath + sr.Name);
System.ChDir('..');
end;
Windows.DeleteFile(Pchar(SourcePath + sr.Name));
until FindNext(sr) <> 0;
Windows.FindClose(sr.FindHandle);
RemoveDir(SourcePath);
end;
// Screen.Cursor:=crDefault;
end;
var ss:Tsearchrec;
filepath:string;
begin
filepath:='c:\';
listbox1.Items.Clear;
if findfirst(filepath+'*.*',faAnyFile,ss)=0 then
begin
if not ((ss.Attr and fadirectory)=fadirectory) then
listbox1.Items.Add(ss.Name);
while findnext(ss)=0 do
begin
if not ((ss.attr and fadirectory)=fadirectory) then
listbox1.Items.Add(ss.Name);//可添加路径,如: filepath+ss.name;
end;
findclose(ss);
end;
end;