creating files, recursively creating directories

System.IO.Directory.CreateDirectory() will create all directories and subdirectories in a specified path, should they not already exist.

You can call it, passing the path, to ensure the folder structure is created prior to writing your file.


here is how I usually do it

Directory.CreateDirectory(Path.GetDirectoryName(filePath));

^ this should take care of ensuring all necessary folders (regardless if some of them already exist) that precedes your file are created. E.g. if you pass it "c:/a/b/c/data/my file.txt", it should ensure "c:/a/b/c/data" path is created.


While System.IO.Directory.CreateDirectory() will indeed create directories for you recursively, I came across a situation where I had to come up with my own method. Basically, System.IO doesn't support paths over 260 characters, which forced me to use the Delimon.Win32.IO library, which works with long paths, but doesn't create directories recursively.

Here's the code I used for creating directories recursively:

void CreateDirectoryRecursively(string path)
{
    string[] pathParts = path.Split('\\');

    for (int i = 0; i < pathParts.Length; i++)
    {
        if (i > 0)
            pathParts[i] = Path.Combine(pathParts[i - 1], pathParts[i]);

        if (!Directory.Exists(pathParts[i]))
            Directory.CreateDirectory(pathParts[i]);
    }
}

Tags:

C#