提问人:Matthew2004 提问时间:11/13/2023 更新时间:11/13/2023 访问量:38
如何复制和替换多个目录?[已结束]
How can i copy and replace multiple directories? [closed]
问:
所以我试图复制多个目录,然后用其中的文件替换多个目录。 我该怎么做?我知道如何使用 Files.Copy 复制多个文件,但我无法用目录弄清楚。
答:
0赞
Lajos Arpad
11/13/2023
#1
请参阅 https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories
using System.IO;
CopyDirectory(@".\", @".\copytest", true);
static void CopyDirectory(string sourceDir, string destinationDir, bool recursive)
{
// Get information about the source directory
var dir = new DirectoryInfo(sourceDir);
// Check if the source directory exists
if (!dir.Exists)
throw new DirectoryNotFoundException($"Source directory not found: {dir.FullName}");
// Cache directories before we start copying
DirectoryInfo[] dirs = dir.GetDirectories();
// Create the destination directory
Directory.CreateDirectory(destinationDir);
// Get the files in the source directory and copy to the destination directory
foreach (FileInfo file in dir.GetFiles())
{
string targetFilePath = Path.Combine(destinationDir, file.Name);
file.CopyTo(targetFilePath);
}
// If recursive and copying subdirectories, recursively call this method
if (recursive)
{
foreach (DirectoryInfo subDir in dirs)
{
string newDestinationDir = Path.Combine(destinationDir, subDir.Name);
CopyDirectory(subDir.FullName, newDestinationDir, true);
}
}
}
此方法获取 a 和 参数 as ,分别指定从何处复制和复制到何处。 是一个标志,它决定了我们是否需要复制子目录和子子目录等的内容。sourceDir
destinationDir
string
recursive
bool
首先,我们定义为 的 。然后,我们将其中的目录缓存到 via .然后,我们根据 和 循环创建目录,并将 复制到 ,这是通过与文件名组合来定义的。dir
DirectoryInfo
sourceDir
dirs
dir.GetDirectories()
destinationDir
dir.GetFiles()
file
targetFilePath
destinationDir
如果设置为 true,则我们循环目录并调用每个目录。recursive
CopyDirectory
如果你有多个目录要复制,那么你可以把它们放在一个数组或集合或其他东西中,循环它并调用每个目录。CopyDirectory
评论
0赞
Matthew2004
11/13/2023
是的,这有效,但是它向我抛出System.IO.IOException:“文件'C:\Users\werni\Desktop\docelowy\barter\item_barter_electr_militaryboard\item_barter_electr_militaryboard.bundle'已经存在。因此,它看起来像是复制了第一个文件夹,然后停止并抛出该错误。
0赞
Fildor
11/13/2023
这就是 File.Copy 的作用。您希望如何处理错误?@Matthew2004
0赞
Lajos Arpad
11/13/2023
@Matthew2004,您可以检查该文件夹是否存在,如果存在,则跳过它。
上一个:共享 Excel 工作表
评论