我正在使用下面的代码使一个文件夹在网络上可用。该文件夹有、子文件夹和文件,共有455个文件和13个文件夹,大小409 MB。
我的方法是递归地调用自己,以便在其中创建子文件夹和文件的副本。总的来说,这个方法需要超过10分钟才能完成任务,我希望加快这个过程。
到目前为止,我已经浏览了不同的帖子,但没有找到更好的解决方案。是否有更好的方法来完成我的任务,或者对我的代码进行任何改进以加快执行速度?
void CopyDirectoryAndFiles(string sourceDirectory, string destinationDirectory, bool recursive)
{
// Get information about the source directory
var dir = new DirectoryInfo(sourceDirectory);
// 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(destinationDirectory);
// Get the files in the source directory and copy to the destination directory
foreach (FileInfo file in dir.GetFiles())
{
string targetFilePath = Path.Combine(destinationDirectory, file.Name);
file.CopyTo(targetFilePath);
}
// If recursive and copying subdirectories, recursively call this method
if (recursive)
{
foreach (DirectoryInfo subDir in dirs)
{
string newDestinationDirectory= Path.Combine(destinationDirectory,subDir.Name);
CopyDirectoryAndFiles(subDir.FullName, newDestinationDirectory, true);
}
}
}
谢谢你的帮助。
发布于 2022-06-26 15:02:18
我不认为有办法大幅度提高业绩,但我可以提出几点建议:
foreach
w/ Parallel.ForEach
来复制多个流中的数据;xcopy
),并从C#代码中调用该工具。如果指定/e
标志.,xcopy可以递归地复制文件夹。
https://stackoverflow.com/questions/72765640
复制相似问题