Delphi判断一个路径是目录还是文件

 1 unit Unit1;
 2 
 3 interface
 4 
 5 uses
 6   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 7   Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
 8 
 9 type
10   TForm1 = class(TForm)
11     Button1: TButton;
12     ListBox1: TListBox;
13     procedure Button1Click(Sender: TObject);
14   private
15     { Private declarations }
16     function IsFileOrDir(AFilePath: string): Integer;
17     function ShowFileTabPath(AFilePath: string): string;
18   public
19     { Public declarations }
20   end;
21 
22 var
23   Form1: TForm1;
24 
25 implementation
26 
27 {$R *.dfm}
28 
29 procedure TForm1.Button1Click(Sender: TObject);
30 var
31   SearchRec:TSearchRec;
32   nResult:Integer;
33 const
34   szFilePath='C:UserszhujqDesktop新建文件夹 (3)*.*';
35 begin
36   ListBox1.Clear; //填充ListBox
37   nResult:=FindFirst(szFilePath,faAnyFile,SearchRec);  //查找第一个文件
38   while nResult=0 do  //如果返回值为0表示找到文件
39   begin
40     ListBox1.Items.Add(ShowFileTabPath(ExtractFilePath(szFilePath)+SearchRec.Name));//将文件添加到ListBox,ExtractFilepath函数用于提取文件路径
41     nResult:=FindNext(SearchRec);  //继续查找下一个文件,至到返回值不为0时
42   end;
43 
44 end;
45 
46 function TForm1.IsFileOrDir(AFilePath: string): Integer;
47 var
48   C: Cardinal;
49 begin
50   Result := -1;
51   C := GetFileAttributes(Pchar(AFilePath));//把string转换为PAnsiChar
52   if C = $FFFFFFFF then
53   begin
54     // 文件或文件夹不存在
55     Result := 0;
56     Exit;
57   end
58   else if C and FILE_ATTRIBUTE_DIRECTORY <> 0 then
59   begin
60     // 是文件夹不是文件
61     Result := 1;
62     Exit;
63   end
64   else
65   begin
66      // 是文件
67     Result := 2;
68     Exit;
69   end;
70 end;
71 
72 function TForm1.ShowFileTabPath(AFilePath: string): string;
73 begin
74   Result := '';
75   case IsFileOrDir(AFilePath) of
76     0:
77     begin
78       Result := AFilePath + '  0';
79     end;
80     1:
81     begin
82       Result := AFilePath + '  1';
83     end;
84     2:
85     begin
86       Result := AFilePath + '  2';
87     end;
88   end;
89 end;
90 
91 end.
原文地址:https://www.cnblogs.com/FKdelphi/p/13610825.html