频道分类

delphi 取文件目录下所有文件名和文件目录名

作者:admin 来源: 日期:2020/3/8 13:33:43 人气: 标签:

 
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;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}


uses
  // Delphi
 ShlObj, ActiveX, Character, Math, DateUtils;


function IsDirectory(const DirName: string): Boolean;
begin
  Result := DirectoryExists(DirName);
end;


function ListFiles(const Dir, Wildcard: string; const List: TStrings; IncludeDirs: Boolean = True; RelativeNames: Boolean = False): Boolean;
var
  FileSpec: string;   // full file spec of a wildcard
  Path: string;       // full path of directory, including training backslash
  SR: TSearchRec;     // file search result
  Success: Integer;   // success code for FindXXX routines
const
  faVolumeId = $00000008; // redefined from SysUtils to avoid deprecated warning
begin
  Assert(Assigned(List), 'ListFiles: List is nil');
  // Check if true directory and exit if not
  Result := IsDirectory(Dir);
  if not Result then
    Exit;
  // Build FileSpec from directory and wildcard
  FileSpec := IncludeTrailingPathDelimiter(Dir);
  if Wildcard = '' then
    FileSpec := FileSpec + '*.*'
  else
    FileSpec := FileSpec + Wildcard;
  Path := IncludeTrailingPathDelimiter(Dir);
  // Do search
  Success := FindFirst(FileSpec, faAnyFile, SR);
  try
    while Success = 0 do
    begin
      // only add true files or directories to list
      if (SR.Name <> '.') and (SR.Name <> '..')
        and (SR.Attr and faVolumeId = 0)
        and (IncludeDirs or not IsDirectory(Path + SR.Name)) then
        if RelativeNames then
          List.Add(SR.Name)
        else
          List.Add(Path + SR.Name);
      Success := FindNext(SR);
    end;
  finally
    System.SysUtils.FindClose(SR);
  end;
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
ListFiles('C:\Users\xxx\Desktop\codesnip-develop\codesnip-develop','*.*',memo1.Lines,true{是否获取文件目录},true{是否只显示文件名});
end;

end.

上一篇:delphi IsDirectory 判断是否是目录下一篇:没有资料