Search code examples
c#asp.netfilefile-iocreate-directory

Automatically create directories from long paths


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?


Solution

  • 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>.