views:

122

answers:

2

I want to copy the file c:\a1\b2\c3\foo.txt to d:\a1\b2\c3\foo.txt. The subdirectories don't exist on the D drive, and if I try to do a direct CopyTo() I'll get an IO exception. I haven't been able to find any built-in c# function that does the dirty work of creating the missing directories. So I wrote this:

FileInfo file = new FileInfo(@"c:\a1\b2\c3\foo.txt");
DirectoryInfo destDir = new DirectoryInfo(file.DirectoryName.Replace("c:", "d:");

if (!destDir.Exists) // false
    CreateDirectory(destDir, null);
file.CopyTo(file.FullName.Replace("c:", "d:"), true);

private void CreateDirectory(DirectoryInfo endDir, Stack<DirectoryInfo> trail)
{
    if (trail == null)
    {
        trail = new Stack<DirectoryInfo>();
        trail.Push(endDir);
    }

    // remove last directory - c:\a1\b2\c3, c:\a1\b2, c:\a1
    Match theMatch = Regex.Match(endDir.FullName, @".*(?=\\\w*\Z)"); 
    DirectoryInfo checkDir = new DirectoryInfo(theMatch.ToString());
    if (!checkDir.Exists)
    {
        trail.Push(checkDir);
        CreateDirectory(checkDir, trail);
    }
    else
        foreach (DirectoryInfo dir in trail)
            Directory.CreateDirectory(dir.FullName);
}

That's pretty involved, and as they like to say on late-night informercials, "There's got to be a better way!"

Question: how would I make the function above move efficient? And am I missing a built-in method that already does everything I'm doing the hard way?

+3  A: 
Directory.CreateDirectory(@"c:\foo\bar\baz");

Documented as creating all required directories, and works for me.

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.

Michael Petrotta
I guess that does mean I was being way too involved. Thanks! That's what I was afraid of :)
Drakestar
+2  A: 

Or you can just use Directory.CreateDirectory() directly, since it already creates all the intermediate paths.

jerryjvl