Path is file or directory (folder)

4

How do I check if a path points to a file or folder? I have no idea how to do it.

A folder or directory path would be:

C:\Program Files\Embarcadero\RAD Studio.0\bin

A file:

C:\Program Files\Embarcadero\RAD Studio.0\bin\bds.exe
    
asked by anonymous 28.10.2014 / 23:43

4 answers

6

A secure way to check if it's directory is as follows:

function IsDirectory(const Path: String): Boolean;
var
  F: TSearchRec;
  NormPath: String;
begin
  NormPath:= ExcludeTrailingPathDelimiter(Path);
  if FindFirst(NormPath, faDirectory, F) = 0 then
  begin
    Result:= (F.Attr and faDirectory) <> 0;
    FindClose(F);
  end
  else
  begin
    Result:= False;
    //Mensagem adicional que caminho não existe, se desejar
  end;
end;

I prefer this way, because I will have to identify if there is a path and can tell if it is a file or folder.

    
29.10.2014 / 12:32
1

Following the tip of @Bacco and @bfavaretto and taking the time to pass a path to documentation, the correct one would be the function:

function isFolder(dir:string):boolean;
begin
  Result := DirectoryExists(dir);
end;

A good repository for delphi Run Time Library (RTL) types and functions is DeplhiBasics, such as this link on Directory Exists

    
29.10.2014 / 11:24
0

With the @Raul tip, I did this function:

function isFolder(dir:string):boolean;
var
fof : boolean;
begin
if FileExists(dir) then
fof := false
else
fof := true;
Result := fof;
end;

If true, it is a folder, if false, a file.

    
29.10.2014 / 00:05
0

Improving this function a little:

function isFolder(dir:string):boolean;
begin
  Result := not FileExists(dir);
end;
    
17.03.2015 / 11:58