I searched on net and have found c# code to copy file async with progress bar which is working perfectly. Now I am trying to copy a folder having multiple files. I have added an extra progress bar, but the new progress bar finishes quickly without any wait.
I am putting code here:
private void button1_Click(object sender, EventArgs e)
{
var _source = txtSource.Text;
var _destination = txtDestination.Text;
Task.Run(() =>
{
CopyFoldersRecursively(_source, _destination, x => progressBar1.BeginInvoke(new Action(() => { progressBar1.Value = x; })));
}).GetAwaiter().OnCompleted(() => progressBar1.BeginInvoke(new Action(() => { progressBar1.Value = 100; })));
}
public void CopyFoldersRecursively(string sourcePath, string targetPath, Action<int> progressCallback)
{
try
{
// Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
}
// Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
{
var _source = new FileInfo(newPath);
var _destination = new FileInfo(targetPath + @"\" + Path.GetFileName(_source.ToString()));
Task.Run(() =>
{
_source.CopyTo(_destination, x => progressBar2.BeginInvoke(new Action(() => { progressBar2.Value = x; lblPercent2.Text = x.ToString() + "%"; })));
}).GetAwaiter().OnCompleted(() => progressBar2.BeginInvoke(new Action(() => { progressBar2.Value = 100; lblPercent2.Text = "100%"; })));
}
}
catch (Exception ex)
{
throw ex;
}
}
public static class FileInfoExtension
{
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();
}
}
}