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)
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);
}
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?
source
share