-
Copying Files and Directories With Progress in C#
Posted on February 13th, 2010 No commentsThe .Net Framework doesn’t have any method to copy directories recursively. It doesn’t either support getting progress on file copies. So I decided to write two extension methods to fill up the gap.
Features
These extension methods are attached to FileInfo and DirectoryInfo and allow you to:
- Copy a single file with progress notifications.
- Copy a directory recursively with or without progress notifications.
- The progress updates includes the number of bytes transferred and the total number of bytes being copied, both for the currently transferring file, and for the whole operation.
- The progress updates also include the filename being currently copied.
Behind the scenes I use Interop to call CopyFileEx and the code is fairly optimized but it should also be simple to adapt it to your needs.
Usage
To copy a file and display progress, you first create a FileInfo instance for the file you want to copy, then you call the new extension method.
var fileInfo = new FileInfo("C:/Copy/This.file"); fileInfo.CopyTo("C:/Dest/Folder", (p) => { Progress = (double)p.BytesTransferred / p.TotalBytes; });
If you want to copy a folder, you get some more progress information, as you can see here:
var dirInfo = new DirectoryInfo("C:/Copy/From/"); dirInfo.CopyTo("C:/Copy/To/", (p) => { TotalProgress = (double)p.BytesTransferred / p.TotalBytes; FileProgress = (double)p.CurrentFileTransferred / p.CurrentFileSize; CurrentFile = p.CurrentFileName; });
Download
The code can be downloaded here, CopyExtensions.cs. Enjoy!
This work is in the Public Domain.
Leave a reply



