views:

59

answers:

5

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?

A: 
string somepath = @"z:/root/test/thing1/thing2/file.txt";
Directory.CreateDirectory( Path.GetDirectoryName( somepath ) );
Joel Lucsy
A: 

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);
Homam
+1  A: 
Directory.CreateDirectory("/root/...") 

Creates all directories and subdirectories in the specified path

A_Nablsi
Agreed, no need to check if directory exists as it does this internally.
Squirrel
+5  A: 
foreach (string sRelativePath in dicFiles.Keys)
{
    string sFullPath = Path.Combine(sDefaultLocation, sRelativePath);
    string sDirectory = Path.GetDirectoryName(sFullPath);

    Directory.CreateDirectory(sDirectory);

    saveFile(sFullPath, dicFiles[sRelativePath]);
}

where dicFiles is something like a Dictionary<string, object>.

GCATNM
A: 
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.

Steve Townsend