Path is file or directory (folder)

Asked

Viewed 3,097 times

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\10.0\bin

A file:

C:\Program Files\Embarcadero\RAD Studio\10.0\bin\bds.exe
  • 2

    You can do a check to see what it is, a suggestion would be For directory, try the command if Directoryexists('c: path') then ... E for file use: if Fileexists(filename) then

4 answers

6


A safe way to check if it is 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 how to identify if there is the path and also be able to say if it is file or folder.

  • Actually, this way the function is much more robust, besides being able to return to the user the information whether or not he selected a file for example

1

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

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

A good repository to know the types and functions of the RTL (Run Time Library) of Delphi is Deplhibasics, for example this link about the function Directory Exists

  • 1

    Good answer, there is a small problem, however, which is why I prefer the approach I always use, which is to use Tsearchrec. Because, when there is no file, the function isFolder you made returns false, without the possibility to identify if it really is not folder, or if the path does not exist

0

With @Raul’s 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 it returns true, it is a folder, if false, a file.

  • 2

    I don’t know anything about Delphi, but it seems that this function will return a false positive if you pass the path of a non-existent file, no?

  • 3

    It would be nice to learn to work with Boolean. In virtually no language does it make sense to use if much less else to return logical value. What you did with a lot of lines is the same thing as writing only Not FileExists() Besides, as Raul said, you should use DirectoryExists(). As bfavaretto said, if the file does not exist, its function will find that it is a directory.

  • 1

    I suggest removing that answer, since it is wrong.

0

Improving this function a little:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.