Tutorial :CopyTo() to a directory that doesn't yet exist


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?



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.


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


Strange, I am working with CopyTo and it creates all the subdirectories automatically in the destination location.

My code is as simple as can be:

// file is FileInfo and target is DirectoryInfo  file.CopyTo(target);  


A DirectoryInfo instance can create its own path with all the checking you want via destDir.Create():

FileInfo file = new FileInfo(@"c:\a1\b2\c3\foo.txt");  DirectoryInfo destDir = new DirectoryInfo(file.DirectoryName.Replace("c:", "d:");    destDir.Create(); // <-- makes it if it doesn't exist, otherwise noop    var newPath =      Path.Combine(destDir.FullName, Path.GetFileName(file)); // <-- just to be safe...  file.CopyTo(newPath, true);  

Found this out here: https://stackoverflow.com/a/2955425/1037948

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »