Quantcast
Channel: Delphi – The Wiert Corner – irregular stream of stuff
Viewing all articles
Browse latest Browse all 1440

Delphi: do not do “if (not DirectoryExists(path)) then ForceDirectories(path))”

$
0
0

During code reviews, I often see people do things like this:

if (not DirectoryExists(Path)) then
  ForceDirectories(Path))

or this:

if (not TDirectory.Exists(Path)) then
  TDirectory.CreateDirectory((Path))

Half a year ago, I wrote about .NET/C#: do not do “if (!Directory.Exists(path)) Directory.CreateDirectory(path))”.

The same holds for since Delphi XE introduced the ForceDirectories method in the SysUtils and FileCtrl units and the TDirectory.CreateDirectory method in the IOUtils unit.

You don’t need the if statements here in Delphi either: The methods ForceDirectories and TDirectory.CreateDirectory (that internally calls ForceDirectories) will do nothing if the directory already exists

So your code only needs to be like this:

ForceDirectories(Path));

or this:

TDirectory.CreateDirectory((Path));

This is how a simplified ForceDirectories method implementation looks like:

function ForceDirectories(Dir: string): Boolean;
begin
  Result := True;
  if Dir = '' then
    raise EInOutError.CreateRes(@SCannotCreateDir);
  Dir := ExcludeTrailingPathDelimiter(Dir);
  if (Dir = '') or DirectoryExists(Dir) then Exit;
  Result := ForceDirectories(ExtractFilePath(Dir)) and CreateDir(Dir);
end;

–jeroen

via: .NET/C#: do not do “if (!Directory.Exists(path)) Directory.CreateDirectory(path))” « The Wiert Corner – irregular stream of stuff.


Filed under: Delphi, Delphi XE, Delphi XE2, Delphi XE3, Delphi XE4, Development, Software Development

Viewing all articles
Browse latest Browse all 1440

Trending Articles