C# 有效地复制多个文件
我必须把相当多的文件从一个文件夹复制到另一个文件夹。目前我是这样做的:C# 有效地复制多个文件,c#,.net,file,copy,C#,.net,File,Copy,我必须把相当多的文件从一个文件夹复制到另一个文件夹。目前我是这样做的: string[] files = Directory.GetFiles(rootFolder, "*.xml"); foreach (string file in files) { string otherFile = Path.Combine(otherFolder, Path.GetFileName(file)); File.Copy(file, otherFile); } 这是最有效的方法吗?似乎需要
string[] files = Directory.GetFiles(rootFolder, "*.xml");
foreach (string file in files)
{
string otherFile = Path.Combine(otherFolder, Path.GetFileName(file));
File.Copy(file, otherFile);
}
这是最有效的方法吗?似乎需要很长时间
编辑:我真的在问是否有一种更快的方法来批量复制,而不是复制单个文件,但我想答案是否定的。您可以使用操作系统来移动文件。这就是像WinMerge这样的工具所做的。您单击应用程序中的“复制”按钮,它会弹出Windows进度框,就像您使用资源管理器安排复制一样。描述它。我想不出比File.Copy更有效的方法,它直接进入操作系统
另一方面,如果需要那么长的时间,我强烈建议显示一个进度对话框,就像为您做的那样。至少您的用户会知道发生了什么。我最近在VB.NET中使用filestreams实现了我的文件副本:
fsSource = New FileStream(backupPath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None, 1024, FileOptions.WriteThrough)
fsDest = New FileStream(restorationPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, FileOptions.WriteThrough)
TransferData(fsSource, fsDest, 1048576)
Private Sub TransferData(ByVal FromStream As IO.Stream, ByVal ToStream As IO.Stream, ByVal BufferSize As Integer)
Dim buffer(BufferSize - 1) As Byte
Do While IsCancelled = False 'Do While True
Dim bytesRead As Integer = FromStream.Read(buffer, 0, buffer.Length)
If bytesRead = 0 Then Exit Do
ToStream.Write(buffer, 0, bytesRead)
sizeCopied += bytesRead
Loop
End Sub
更新进度条(使用sizeCopied)并在需要时取消文件传输(使用IsCancelled)似乎是一种快速而简单的方法。您不知道吗,添加进度条后,事情实际上进展得更快。至少,这是用户会告诉你的。