我正在尝试在我的WPF应用程序中移动文件夹,同时查看进度条。移动操作非常缓慢,我找不到任何解决方案来提高速度(测试速度是38 Mb移动需要2:30分钟)。但我不知道如何有效地移动它。目前的移动方式虽然能用,但效率极低。
public delegate void ProgressChangeDelegate(double percentage);
public delegate void CompleteDelegate();
class FileMover
{
public string SourceFilePath { get; set; }
public string DestFilePath { get; set; }
public event ProgressChangeDelegate OnProgressChanged;
public event CompleteDelegate OnComplete;
public FileMover(string Source, string Dest)
{
SourceFilePath = Source;
DestFilePath = Dest;
OnProgressChanged += delegate { };
OnComplete += delegate { };
}
public void Copy()
{
byte[] buffer = new byte[1024 * 1024]; // 1MB buffer
using (FileStream source = new FileStream(SourceFilePath, FileMode.Open, FileAccess.Read))
{
long fileLength = source.Length;
using (FileStream dest = new FileStream(DestFilePath, FileMode.CreateNew, FileAccess.Write))
{
long totalBytes = 0;
int currentBlockSize = 0;
while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytes += currentBlockSize;
double percentage = (double) totalBytes * 100.0 / fileLength;
dest.Write(buffer, 0, currentBlockSize);
OnProgressChanged(percentage);
}
}
}
OnComplete();
}
}
private async void MoveFile(string source, string outDir)
{
if (!string.IsNullOrEmpty(outDir) && !string.IsNullOrEmpty(source))
{
//InputButtonText.Text = "Please be patient while we move your file.";
//Task.Run(() => { new FileInfo(source).MoveTo(Path.Combine(outDir, Path.GetFileName(source))); }).GetAwaiter().OnCompleted(
// () =>
// {
// OutputScanned.ItemsSource = null;
// InputButtonText.Text = "Click to select a file";
// });
var mover = new FileMover(source, Path.Combine(outDir, Path.GetFileName(source)));
await Task.Run(() => { mover.Copy(); });
mover.OnProgressChanged += percentage =>
{
MoveProgress.Value = percentage;
InputButtonText.Text = percentage.ToString();
};
mover.OnComplete += () => { File.Delete(source); };
}
}
System.IO.File.Move()
方法。只要文件在同一卷中移动,这个操作就非常快,而且独立于文件大小。如果你试图跨卷移动,文件将被复制而不是移动(如果你想要删除源文件,你必须自己删除),但操作仍然会高效完成。 - Peter DunihoSystem.IO.File.Move()
,您会建议他们如何显示此移动的进度? - Trevor