gpt4 book ai didi

c# - CopyTo() 到一个尚不存在的目录

转载 作者:行者123 更新时间:2023-11-30 19:00:50 30 4
gpt4 key购买 nike

我想将文件 c:\a1\b2\c3\foo.txt 复制到 d:\a1\b2\c3\foo.txt。 D 驱动器上不存在子目录,如果我尝试直接执行 CopyTo(),则会出现 IO 异常。我一直没能找到任何内置的 c# 函数来完成创建丢失目录的肮脏工作。所以我写了这个:

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

这非常复杂,正如他们喜欢在深夜的电视广告中所说的那样,“一定有更好的方法!”

问题:我怎样才能使上面的函数移动更有效率?我是否错过了一个内置方法,它已经完成了我正在做的所有事情?

最佳答案

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

Documented就像创建所有必需的目录一样,对我有用。

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.

关于c# - CopyTo() 到一个尚不存在的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/961100/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com