File Copy Progress not reporting status correctly

madaxe2021

Member
Joined
Jun 25, 2021
Messages
6
Programming Experience
3-5
I found this on the web it does exactly what I want it to do but dependent on file size it will not report out at 100% in the action, I think it has something to do with the amount of bytes being read and this is not reflected in the progressCallback

anybody have any suggestions?

Thanks

Madaxe


CopyTo:
public static void CopyTo(this FileInfo file, FileInfo destination, Action<int> progressCallback)
        {
            const int bufferSize = 1024 * 1024;
            byte[] buffer = new byte[bufferSize], buffer2 = new byte[bufferSize];
            bool swap = false;
            int progress = 0, reportedProgress = 0, read = 0;
            long len = file.Length;
            float flen = len;
            Task writer = null;
            using (var source = file.OpenRead())
            using (var dest = destination.OpenWrite())
            {
                dest.SetLength(source.Length);
                for (long size = 0; size < len; size += read)
                {
                    if ((progress = ((int)((size / flen) * 100))) != reportedProgress)
                        progressCallback(reportedProgress = progress);

                    read = source.Read(swap ? buffer : buffer2, 0, bufferSize);
                    writer?.Wait();
                    writer = dest.WriteAsync(swap ? buffer : buffer2, 0, read);
                    swap = !swap;
                }
                writer?.Wait();
            }
        }
 
i found a cheese fix it works, which is to set the progressCallback to 100% before the final wait

Crappy FIx:
                progressCallback(100);
                writer?.Wait();
 
Shouldn't you set it to 100% after the last write completes? Otherwise you are giving misleading feedback about the copy having completed, but there is actually still more work to be done.
 
I found this on the web it does exactly what I want it to do but
It clearly doesn't do what you want it to if you are looking for help in altering it.

If you have 3-5 years exp as your profile suggests, I'd really expect you to be writing your own code.

Looks like your problem might be caused by the long declaration on line 14. You can see a cleaner way of writing it in the example linked below.

If you used a background worker, you could replicate the same outcome but easier using some simple maths to calculate the byte size of the file, and how much of the file has been copied. You also don't need to delegate as the background worker will do that for you through its report progress method. BackgroundWorker.ReportProgress Method (System.ComponentModel)
 
Back
Top Bottom