Looking for File Copy function in C#
I'm writing a tool that performs copying from USB devices to the开发者_StackOverflow社区 local HD - I wonder if there is a function in C# to copy a file from one path to another?
Yes! The cunningly named:
File.Copy
File.Copy
is probably OK for what you want to do, but it doesn't provide much flexibility (no cancellation, no progress tracking...).
If you need those features, you can look at the CopyFileEx
API, which supports them. I wrote a .NET wrapper for CopyFileEx
(and also MoveFileWithProgress
), you can find it here (documentation comments are in French, sorry about that... hopefully that won't be an issue). Here's how you can use it:
void CopyFile(string source, string destination)
{
var copy = new FileCopyOperation(source, destination);
copy.ReplaceExisting = true;
copy.ProgressChanged += copy_ProgressChanged;
copy.Execute();
}
void copy_ProgressChanged(object sender, FileOperationProgressEventArgs e)
{
copyProgressBar.Value = e.PercentDone;
if (abortRequested)
e.Action = FileOperationProgressAction.Cancel;
}
精彩评论