1. 程式人生 > 實用技巧 >Delphi判斷一個路徑是目錄還是檔案

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:\Users\zhujq\Desktop\新建資料夾 (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.