Solved

How to empty a directory leaving one file?

Posted on 2006-06-26
2
267 Views
Last Modified: 2010-04-05
Hi my dear friends!

This is what I have and this works great:

*******************************************************************************
 function KillFiles(Path: string): Boolean;
var
  Found:         Integer;
  Attr:          Integer;
  SearchRec:     TSearchRec;
  FileName:      string;

begin
  Attr := faAnyFile;
  Found := FindFirst(Path + '\*.*', Attr, SearchRec);
  while (Found=0) do
  try
    if ((IntToHex(SearchRec.Attr, 8)='00000810')
    or  (IntToHex(SearchRec.Attr, 8)='00000010'))
    and (not (SearchRec.Name[1]='.')) then
    begin
      FileName := Path + '\' + SearchRec.Name;
      RemoveDir(FileName);
      KillFiles(FileName);
    end;
    if (not ((SearchRec.Attr=faDirectory) or (SearchRec.Attr=17))
    and not (SearchRec.Name='.') and not (SearchRec.Name='..')) then
    begin
      FileName := Path + '\' + SearchRec.Name;
      if ((FileGetAttr(FileName) and faReadOnly) > 0) then
        FileSetAttr(FileName, FileGetAttr(FileName) xor faReadOnly);

      if ((FileGetAttr(FileName) and faHidden) > 0) then
        FileSetAttr(FileName, FileGetAttr(FileName) xor faHidden);

      if ((FileGetAttr(FileName) and faSysFile) > 0) then
        FileSetAttr(FileName, FileGetAttr(FileName) xor faSysFile);

      DeleteFile(FileName);
      KillFiles(Path);
    end;
    Found := FindNext(SearchRec); //get next file in directory
  except
  end;
  FindClose(SearchRec);
end;

procedure TForm1.btnDeleteClick(Sender: TObject);
var i : cardinal;
user:string;
begin
  i:=255;
//ExtractFilePath('c:\documents and settings\');
setlength(user,i);
getusername(pchar(user),i);
setlength(user,(i-1));
//ShowMessage(user);
if not
  killfiles('c:\documents and settings\'+user+'\local settings\temporary internet files\content.ie5')
  then ShowMessage('failed!');

  end;

end.

***************************************************************************
Thanks to esoftbg and inthe btw :)

Now I want this program to leave one file unharmed untouched.....the index.dat....

How should I implement this? I'd say there would be other ways of emptying the cache of IE but so far this is my solution any other solutions are welcome as well ofcourse!

Best regards,

Paul

Ps working samples always do the trick ofcourse!
0
Comment
Question by:PeterdeB
2 Comments
 
LVL 26

Accepted Solution

by:
Russell Libby earned 125 total points
ID: 16989442
Paul,

Here is another way using the SHFileOperation from the ShellApi unit. It keeps you from having to recurse the paths, and uses the same logic (code) that windows uses when deleting files/folders. Full example provided, let me know if you have questions.

Regards,
Russell

-----

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  ShellApi, StdCtrls;

type
  TForm1            = class(TForm)
     Button1:       TButton;
     procedure      Button1Click(Sender: TObject);
  private
     // Private declarations
     function       UserName: String;
  public
     // Public declarations
  end;

var
  Form1:            TForm1;

implementation
{$R *.DFM}

function TForm1.UserName: String;
var  dwSize:        DWORD;
begin

  // Buffer size to use
  dwSize:=256;

  // Allocate result buffer
  SetLength(result, 256);

  // Get user name
  if GetUserName(Pointer(result), dwSize) then
     // Truncate to actual result
     SetLength(result, Pred(dwSize))
  else
     // Truncate to null string
     SetLength(result, 0);

end;

function DeleteExclude(Path: String; ExcludeFile: String): Boolean;
var  lpFileOp:      TSHFileOpStruct;
     srFind:        TSearchRec;
     dwFind:        Integer;
     szPath:        String;
     szList:        String;
begin

  // Set default delete list
  SetLength(szList, 0);

  // Make sure path is correct
  szPath:=ExcludeTrailingBackSlash(Path);

  // Init the find
  dwFind:=FindFirst(szPath+'\*.*', faAnyFile, srFind);

  // Check find
  if (dwFind = 0) then
  begin
     // Resource protection
     try
        // While sucess
        while (dwFind = 0) do
        begin
           // Check name
           if ((Length(srFind.Name) > 0) and not(srFind.Name[1] = '.')) then
           begin
              // Compare against exclusion
              if (CompareText(srFind.Name, ExtractFileName(ExcludeFile)) <> 0) then
              begin
                 // Add to list
                 szList:=szList+szPath+'\'+srFind.Name+#0;
              end;
           end;
           // Find next
           dwFind:=FindNext(srFind);
        end;
     finally
        // Close the find
        FindClose(srFind);
     end;
  end;

  // Check the list
  if (Length(szList) > 0) then
  begin
     // Double null terminate the list
     szList:=szList+#0;
     // Clear struct
     FillChar(lpFileOp, SizeOf(lpFileOp), 0);
     // Set params
     lpFileOp.Wnd:=Application.Handle;
     lpFileOp.wFunc:=FO_DELETE;
     lpFileOp.pFrom:=PChar(szList);
     lpFileOp.pTo:=nil;
     // Remove the FOF_ALLOWUNDO if you don't want this to go in the recycle bin
     lpFileOp.fFlags:=FOF_SILENT or FOF_NOCONFIRMATION or FOF_ALLOWUNDO;
     // Perform the delete
     if (SHFileOperation(lpFileOp) = 0) and (lpFileOp.fAnyOperationsAborted = False) then
        // Success
        result:=True
     else
        // Failure
        result:=False;
  end
  else
     // Nothing to delete
     result:=True;

end;

procedure TForm1.Button1Click(Sender: TObject);
begin

  if DeleteExclude('c:\documents and settings\'+UserName+'\local settings\temporary internet files\content.ie5', 'index.dat') then
     ShowMessage('Success')
  else
     ShowMessage('Failure');

end;

end.
0
 

Author Comment

by:PeterdeB
ID: 16989852
Tnx Russell works great!!

Regards Paul :)
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question