Can I show file copy progress using FileInfo.CopyTo() in .NET?

Jason Down picture Jason Down · Oct 9, 2008 · Viewed 39.7k times · Source

I've created a copy utility in c# (.NET 2.0 Framework) that copies files, directories and recursive sub directories etc. The program has a GUI that shows the current file being copied, the current file number (sequence), the total number of files to be copied and the percentage completed for the copy operations. There is also a progress bar, that is based on current file / total files.

My problem is related to copying large files. I've been unable to find a way to indicate the total copy progress of a large file (using my current class structure that utilitzes FileInfo.CopyTo method). As a workaround I've separated the file copy operations and GUI display to their own threads and set up a visual cue to show that work is being done. At least the user is aware that the program isn't frozen and is still copying files.

It would be nicer to be able to show the progress based on the total number of bytes or have some type of event that fires from the FileInfo.CopyTo method that indicates the total number of bytes copied from the current file.

I'm aware of the FileInfo.Length property, so I'm sure there is a way MacGuyver my own event that is based on this and have a handler on the GUI side of things reading the updates (maybe based on checking the FileInfo.Length property of the destination object using some type of timer?).

Does anyone know of a way to do this that I'm overlooking. If I can avoid it, I'd rather not rewrite my class to copy bytes through a stream and track it that way (though I'm thinking I might be stuck with going that route).

Thanks In Advance

PS - I'm stuck with the .NET 2.0 framework for now, so any solution that requires features available in >= 3.0 only are not an option for me.

PPS - I'm open to solutions in any .NET language variety, not only c#.

Answer

Gaspar Nagy picture Gaspar Nagy · Oct 9, 2008

The FileInfo.CopyTo is basically a wrapper around the Win32 API call "CopyFile" in the kernel32.dll. This method does not support progress callback.

However, the CopyFileEx method does, and you can write your own .NET wrapper around it in a few minutes, like it is described here: http://www.pinvoke.net/default.aspx/kernel32.CopyFileEx