Automatically create directories from long paths
Asked Answered
S

6

17

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?

Smolensk answered 27/10, 2010 at 19:16 Comment(0)
G
23
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>.

Galoshes answered 27/10, 2010 at 19:21 Comment(0)
A
19
string somepath = @"z:/root/test/thing1/thing2/file.txt";
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName( ( somepath ) );
Ahimsa answered 27/10, 2010 at 19:20 Comment(1)
The create Directory.CreateDirectory(somepath) method creates all directories and subdirectories for youCralg
T
8
Directory.CreateDirectory("/root/...") 

Creates all directories and subdirectories in the specified path

Thar answered 27/10, 2010 at 19:21 Comment(1)
Agreed, no need to check if directory exists as it does this internally.Teresitateressa
R
4

Check IO namespace (Directory, Path), I think they'll help you

using System.IO

Then check it..

string fileName =@"d:/root/test/thing1/thing2/file.txt"; 
string directory = Path.GetDirectoryName(fileName);
if (!Directory.Exists(directory))
    Directory.CreateDirectory(directory);
Reynaud answered 27/10, 2010 at 19:21 Comment(0)
O
2
string filename = "c:\\temp\\wibble\\wobble\\file.txt";
string dir = Path.GetDirectoryName(filename);
if (!Directory.Exists(dir))
{
    Directory.CreateDirectory(dir);
}
File.Create(filename);

with suitable exception handling, of course.

Overlong answered 27/10, 2010 at 19:24 Comment(0)
B
0

I've found setting the "default location" at the start of execution to be helpful and reduce a bit of redundant code (e.g., Path.Combine(defaultLocation, relativePath)).

Example:

var defaultLocation = "z:/";
Directory.SetCurrentDirectory(defaultLocation);
Directory.SetCurrentDirectory(AppContext.BaseDirectory);
Biegel answered 30/6, 2017 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.