21

Need some help in creating function which can create folders recursively with giving path:

C:\TestFolder\Another\AndAnother

Delphi function MkDir returning IOerror = 3.

MkDir('C:\TestFolder\Another\AndAnother');

3 Answers 3

72

Use

ForceDirectories('C:\TestFolder\Another\AndAnother');

(This is a standard RTL function, found in SysUtils.pas. Hence you do not need to create your own function, even though that wouldn't have been difficult.)

3
  • 5
    Writing your own ForceDirectories that works on your computer: easy. Writing one that works in the wild handling all the edge cases: hard
    – Ian Boyd
    Apr 20, 2012 at 19:11
  • exactly, all the edge cases make it hard.
    – rocksteady
    Jun 7, 2016 at 10:41
  • 1
    This is not UNC aware, this is why I recommend the new IOUtils library.
    – IceCold
    Aug 31, 2020 at 11:04
4

SysUtils is obsolete now and ForceDirectories is not UNC aware!

There is a new library in since Delphi XE7 (or even earlyer?) called IOUtils.
IOUtils is cross-platform compatible and UNC aware.

function ForceDirectories(FullPath: string): Boolean;   // Works with UNC paths
begin
  TDirectory.CreateDirectory(FullPath);
  Result:= DirectoryExists(FullPath);
end;

Note: The function is from Delphi LightSaber library. There are several other similar I/O functions there (like ListFilesOf(Folder)).

3
  • if we're going to use System.IOUtils, shouldn't we at least use TDirectory.Exists instead of DirectoryExists from SysUtils?
    – Khorkhe
    Sep 4, 2023 at 18:00
  • You are right. but only for the sake of using modern code. DirectoryExists still works (and still not marked as deprecated by Emba). PS: The code looks like this because it is a very very old piece of code from my LightSaber library. This was one of the very first pieces of code in that lib. Back then, IOUtils was very crappy. I mean seriously flawed. So, I tried to use as little as possible from IOUtils.
    – IceCold
    Sep 6, 2023 at 8:28
  • 1
    Anyway, TDirectory.Exists still did not fixed some issues that DirectoryExists had: stackoverflow.com/questions/15166420/…
    – IceCold
    Sep 6, 2023 at 8:40
0

create "folder #1" create "folder #2" inside "folder #1" TDirectory.copy("folder #1","folder #2"); and watch the fun.

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jan 11 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.