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
Filed under: Delphi, Delphi XE, Delphi XE2, Delphi XE3, Delphi XE4, Development, Software Development
