Link to home
Start Free TrialLog in
Avatar of ST3VO
ST3VOFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Deleting all files of a certain file type - URGENT

How can I delete all .tmp files in my application directory please?

Thanks

- ST3VO
Avatar of dinilud
dinilud
Flag of India image

function DeleteFiles(RootDir;FileType:String):Boolean;
var sr: TSearchRec;ParentDir:String;
begin
  if RootDir[length(RootDir)]<>'\' then RootDir:=RootDir+'\';
  ChDir(RootDir);
  if FindFirst(FileType, faAnyFile, sr) = 0 then
  begin
    repeat
      if (sr.Attr and faReadOnly)=faReadOnly then
         SetFileAttributes(pchar(RootDir+sr.Name),sr.Attr and $FE);
      Result:= DeleteFile(RootDir+sr.Name);
    until (not Result) or (FindNext(sr) <> 0);
    FindClose(sr);
  end;
end;


procedure TForm1.FormCreate(Sender: TObject);
begin
   DeleteFiles(ExtractFileDir(Application.ExeName),'*.tmp');
end;
procedure DeleteTMPFiles;
var OwnDir: string;
    SearchRec: TSearchRec;
begin
 // first get our applicationdirectory
 OwnDir := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName));

 // search for all *.tmp files here and delete them
 if FindFirst(OwnDir + '*.tmp', faAnyFile, SearchRec) = 0 then
 repeat
  if not DeleteFile(OwnDir + SearchRec.Name) then
   ShowMessage('can''t delete ' + OwnDir + SearchRec.Name);
 until FindNext(SearchRec) <> 0;

 // close the handle
 FindClose(SearchRec);
end;
hmm, should have checked if there was no new post before posting my solution.

Be aware though, dinilud's solution changes the current directory!
ASKER CERTIFIED SOLUTION
Avatar of dinilud
dinilud
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ST3VO

ASKER

Perfect!!!

Thanks!!!!

-ST3VO
Avatar of ST3VO

ASKER

Yes...I spotted the mistype and changed it to the comma... :) No a problem!!!

Actually there is no changing of directory due to this line
   ChDir(ExtractFileDir(Application.ExeName))
be ware of the changed current dir, might give surprises.
I don't see that line in your code