Automatically create directories from long paths

Brian David Berman picture Brian David Berman · Oct 27, 2010 · Viewed 17.9k times · Source

I have a collection of files with fully qualified paths (root/test/thing1/thing2/file.txt). I want to foreach over this collection and drop the file into the location defined in the path, however, if certain directories don't exist, I want them to great created automatically. My program has a default "drop location", such as z:/. The "drop location" starts off empty, so in my example above, the first item should automatically create the directories needed to create z:/root/test/thing1/thing2/file.txt. How can I do this?

Answer

TeaDrivenDev picture TeaDrivenDev · Oct 27, 2010
foreach (var relativePath in files.Keys)
{
    var fullPath = Path.Combine(defaultLocation, relativePath);
    var directory = Path.GetDirectoryName(fullPath);

    Directory.CreateDirectory(directory);

    saveFile(fullPath, files[relativePath]);
}

where files is IDictionary<string, object>.