Delphi递归删除列表文件以外的所有文件


本文整理自网络,侵删。

 
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Memo2: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure SearchInDir(sDirectory: string);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
begin
  SearchInDir('D:\其他\A我的代码\Fire\bin\VLC');
end;

procedure TForm1.SearchInDir(sDirectory: string);
var
  pSearchRec: TSearchRec; // TSearchRec是delphi为我们定义好的一个记录类型。
  // 用于记录文件的各个参数,比如大小,属性,文件名等等;
  sPath, sFile: string;
begin
  try
    // 检查目录名后面是否有'\'
    if Copy(sDirectory, Length(sDirectory), 1) <> '\' then
      sPath := sDirectory + '\'
    else
      sPath := sDirectory;

    { FindFirst 是用来寻找目标目录下的第一个文件,当成功找到文件时,返回0
      FindFirst的三个参数:1.路径与文件后缀(C:\*.*)
      2.文件类型;
      3.TSearchRec类型变量(用于储存文件的参数) }
    if FindFirst(sPath + '*.*', faAnyFile, pSearchRec) = 0 then
    begin
      repeat
        sFile := Trim(pSearchRec.Name);

        // 排除自身文件夹,与父文件夹
        if sFile = '.' then
          Continue;
        if sFile = '..' then
          Continue;

        sFile := sPath + pSearchRec.Name;

        // 文件夹的情况(递归)
        if (pSearchRec.Attr and faDirectory) <> 0 then
          SearchInDir(sFile)
        else

          // 文件的情况
          if (pSearchRec.Attr and faAnyFile) = pSearchRec.Attr then
          begin
            if Memo2.Lines.IndexOf(sFile) < 0 then
            begin
              DeleteFile(sFile);
              Memo1.Lines.add(sFile);
            end;
          end;

        { FindNext 寻找下一个
          TSearchRec(sr) 是一个文件信息的纪录,
          当FindFirst返回SearchRec时,你可以通过SearchRec.Name获取文件名,
          以及 SearchRec.Size获取文件大小等信息 }
      until FindNext(pSearchRec) <> 0;

      { FindClose 释放由FindFirst分配的内存。FindClose停止一个FindFirst/FindNext序列。
        FindClose 在16位的操作系统中没有用处,但在32位系统中是需要的,
        所以为了最大的FindFirst/FindNext序列完成的可能性应该调用FindClose结束。 }
      FindClose(pSearchRec);

    end;
  except

  end;
end;

end.

相关阅读 >>

Delphi 屏蔽汉字,年月日,时间,银行卡正则表达式

Delphi xe5 使用 android 内置函数几个小测试

Delphi 下载函数

Delphi三层开发小技巧:tclientdataset的delta妙用

Delphi 新建一个txt文档函数

Delphi回调函数高级应用

Delphi中如何实现模糊查找文件

Delphi 动态更改webbrowser数据流内容

Delphi 日期时间函数

Delphi假死线程堵塞解决办法

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...