How to create multiple directories from a single full path in C#?

C#.NetBase Class-Library

C# Problem Overview


If you have a full path like: "C:\dir0\dir1\dir2\dir3\dir4\" how would you best implement it so that all directories are present?

Is there a method for this in the BCL? If not, what's the most elegant way to do this?

C# Solutions


Solution 1 - C#

I would call Directory.CreateDirectory(@"C:\dir0\dir1\dir2\dir3\dir4\").

Contrary to popular belief, Directory.CreateDirectory will automatically create whichever parent directories do not exist.
In MSDN's words, Creates all directories and subdirectories as specified by path.

If the entire path already exists, it will do nothing. (It won't throw an exception)

Solution 2 - C#

Create directories from complete filepath

private String EvaluatePath(String path){
   
    try
    {
        String folder = Path.GetDirectoryName(path);
        if (!Directory.Exists(folder))
        {
            // Try to create the directory.
            DirectoryInfo di = Directory.CreateDirectory(folder);
        }
    }
    catch (IOException ioex)
    {
        Console.WriteLine(ioex.Message);
        return "";
    }
    return path;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoan VengeView Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#Alejandro ArandaView Answer on Stackoverflow