CopyTo () to a directory that does not yet exist

I want to copy the file c: \ a1 \ b2 \ c3 \ foo.txt to d: \ a1 \ b2 \ c3 \ foo.txt. Subdirectories do not exist on drive D, and if I try to make a direct instance of CopyTo (), I will get an IO exception. I could not find the built-in C # function that does the dirty work of creating missing directories. So I wrote the following:

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);
}

It's pretty attractive, and as they like to say on the nightly commercials: "There must be a better way!"

Question: how can I make the function higher efficient? And I don’t have a built-in method that already does everything I do, the hard way?

+2
source share
4 answers
Directory.CreateDirectory(@"c:\foo\bar\baz");

.

, , - . path , . , .

+6

Directory.CreateDirectory() , .

+3

, CopyTo .

, :

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

A DirectoryInfo , 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);

: fooobar.com/questions/23483/...

+1

Source: https://habr.com/ru/post/1709933/


All Articles