我正在尝试在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); };
}
}
移动操作异常缓慢,我找不到使它运行更快的解决方案
可能有很多原因导致移动文件需要这么长时间。例如:反恶意软件应用程序-可能会扫描文件,网络负载(如果移至另一个卷/驱动器),文件大小本身以及可能的代码味道。
[我的猜测是,我想您已经按照处理代码的方式进行了操作,因此您可以处理到目前为止已移动了多少,这很好,但是可以使用alternatives来移动这些文件很好,更快。
一些选项
Win32Native.MoveFile
c ++函数,该函数很好用。Win32.MoveFile
。Kernel32.dll
中的某些功能-这样可以实现完全控制,良好的进度等。我想在短短一分钟内回到上面的内容,因为我想根据您最初发布的内容来说明进度没有更新。
在此await Task.Run(() => { mover.Copy(); });
之前的调用将一直等待,直到完成为止,但是您在此之后注册事件,例如:mover.OnProgressChanged += percentage =>
在Copy()
调用之后,因此,不会,您将不会进行任何更改。
即使您收到更改,您仍然会遇到异常,因为您不在UI线程上,而是在另一个线程上。例如:
mover.OnProgressChanged += percentage =>
{
MoveProgress.Value = percentage;
InputButtonText.Text = percentage.ToString();
};
您正在尝试从另一个线程更新UI(progressbar.value),您根本无法做到这一点。为了解决这个问题,您需要从Dispatcher
中调用。例如:
Application.Current.Dispatcher.Invoke(() =>
{
pbProgress.Value = percentage;
});
返回文件操作
老实说,您仍然可以按照自己的方式做自己想做的事,只需四处走动,您就应该很好。否则,下面我写了一个类,您可以在其中使用该类来移动文件,报告进度等。请参阅下文。
注意:我测试了一个500MB的文件,它在2.78秒内移动了一个文件,并在3.37秒内将850MB的文件从本地驱动器移动到了另一个卷上。
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Transactions; // must add reference to System.Transactions
public class FileHelper
{
#region | Public Events |
/// <summary>
/// Occurs when any progress changes occur with file.
/// </summary>
public event ProgressChangeDelegate OnProgressChanged;
/// <summary>
/// Occurs when file process has been completed.
/// </summary>
public event OnCompleteDelegate OnComplete;
#endregion
#region | Enums |
[Flags]
enum MoveFileFlags : uint
{
MOVE_FILE_REPLACE_EXISTSING = 0x00000001,
MOVE_FILE_COPY_ALLOWED = 0x00000002,
MOVE_FILE_DELAY_UNTIL_REBOOT = 0x00000004,
MOVE_FILE_WRITE_THROUGH = 0x00000008,
MOVE_FILE_CREATE_HARDLINK = 0x00000010,
MOVE_FILE_FAIL_IF_NOT_TRACKABLE = 0x00000020
}
enum CopyProgressResult : uint
{
PROGRESS_CONTINUE = 0,
PROGRESS_CANCEL = 1,
PROGRESS_STOP = 2,
PROGRESS_QUIET = 3,
}
enum CopyProgressCallbackReason : uint
{
CALLBACK_CHUNK_FINISHED = 0x00000000,
CALLBACK_STREAM_SWITCH = 0x00000001
}
#endregion
#region | Delegates |
private delegate CopyProgressResult CopyProgressRoutine(
long TotalFileSize,
long TotalBytesTransferred,
long StreamSize,
long StreamBytesTransferred,
uint dwStreamNumber,
CopyProgressCallbackReason dwCallbackReason,
IntPtr hSourceFile,
IntPtr hDestinationFile,
IntPtr lpData);
public delegate void ProgressChangeDelegate(double percentage);
public delegate void OnCompleteDelegate(bool completed);
#endregion
#region | Imports |
[DllImport("Kernel32.dll")]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("Kernel32.dll")]
private static extern bool MoveFileTransactedW([MarshalAs(UnmanagedType.LPWStr)]string existingfile, [MarshalAs(UnmanagedType.LPWStr)]string newfile,
IntPtr progress, IntPtr lpData, IntPtr flags, IntPtr transaction);
[DllImport("Kernel32.dll")]
private static extern bool MoveFileWithProgressA(string existingfile, string newfile,
CopyProgressRoutine progressRoutine, IntPtr lpData, MoveFileFlags flags);
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("79427A2B-F895-40e0-BE79-B57DC82ED231")]
private interface IKernelTransaction
{
void GetHandle([Out] out IntPtr handle);
}
#endregion
#region | Public Routines |
/// <summary>
/// Will attempt to move a file using a transaction, if successful then the source file will be deleted.
/// </summary>
/// <param name="existingFile"></param>
/// <param name="newFile"></param>
/// <returns></returns>
public static bool MoveFileTransacted(string existingFile, string newFile)
{
bool success = true;
using (TransactionScope tx = new TransactionScope())
{
if (Transaction.Current != null)
{
IKernelTransaction kt = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);
IntPtr txh;
kt.GetHandle(out txh);
if (txh == IntPtr.Zero) { success = false; return success; }
success = MoveFileTransactedW(existingFile, newFile, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, txh);
if (success)
{
tx.Complete();
}
CloseHandle(txh);
}
else
{
try
{
File.Move(existingFile, newFile);
return success;
}
catch (Exception ex) { success = false; }
}
return success;
}
}
/// <summary>
/// Attempts to move a file from one destination to another. If it succeeds, then the source
/// file is deleted after successful move.
/// </summary>
/// <param name="fileToMove"></param>
/// <param name="newFilePath"></param>
/// <returns></returns>
public async Task<bool> MoveFileAsyncWithProgress(string fileToMove, string newFilePath)
{
bool success = false;
try
{
await Task.Run(() =>
{
success = MoveFileWithProgressA(fileToMove, newFilePath, new CopyProgressRoutine(CopyProgressHandler), IntPtr.Zero, MoveFileFlags .MOVE_FILE_REPLACE_EXISTSING|MoveFileFlags.MOVE_FILE_WRITE_THROUGH|MoveFileFlags.MOVE_FILE_COPY_ALLOWED);
});
}
catch (Exception ex)
{
success = false;
}
finally
{
OnComplete(success);
}
return success;
}
private CopyProgressResult CopyProgressHandler(long total, long transferred, long streamSize, long StreamByteTrans, uint dwStreamNumber,CopyProgressCallbackReason reason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData)
{
double percentage = transferred * 100.0 / total;
OnProgressChanged(percentage);
return CopyProgressResult.PROGRESS_CONTINUE;
}
#endregion
}
如何使用
一个例子-
// Just a public property to hold an instance we need
public FileHelper FileHelper { get; set; }
在加载时注册事件...
FileHelper = new FileHelper();
FileHelper.OnProgressChanged += FileHelper_OnProgressChanged;
FileHelper.OnComplete += FileHelper_OnComplete;
这是逻辑...
private async void Button_Click(object sender, RoutedEventArgs e)
{
bool success = await FileHelper.MoveFileAsyncWithProgress("FILETOMOVE", "DestinationFilePath");
}
// This is called when progress changes, if file is small, it
// may not even hit this.
private void FileHelper_OnProgressChanged(double percentage)
{
Application.Current.Dispatcher.Invoke(() =>
{
pbProgress.Value = percentage;
});
}
// This is called after a move, whether it succeeds or not
private void FileHelper_OnComplete(bool completed)
{
Application.Current.Dispatcher.Invoke(() =>
{
MessageBox.Show("File process succeded: " + completed.ToString());
});
}
**:该帮助程序类中还有另一个函数MoveFileTransacted
,您确实不需要此函数,这是另一个帮助程序函数,允许您使用事务移动文件;如果发生异常,文件将不会移动等。