Reputation: 109
I need to display progress while folders are copying (asynchronous).
I'm able to do that with a single file copy, but not with a folder... I just want to display the progress of the overall copy as Windows does.
Here is my code for copying folder:
private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
if (!Directory.Exists(destDirName))
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs, cts.Token);
}
}
}
Then this is called through a button :
await Task.Run(() => DirectoryCopy(
srcFolder,
@"\\" + hostname + @"\C$\" + destFolder + @"\",
true,
cts.Token
));
How can I achieve this?
Tell me if there is not enough information about my issue, I will update my post.
Upvotes: 3
Views: 290
Reputation: 18155
You could make use of IProgress interface.
For example,
private async Task DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, CancellationToken cancellationToken,IProgress<int> progress)
{
// Do work
var percentageProgress = 0;
// percentageProgress = Calculate percentage
progress.Report(percentageProgress);
}
And at the client (believe your button click event),
var progressIndicator = new Progress<int>(ShowProgress);
await UploadPicturesAsync(sourceDirName,destDirName,copySubDirs,token,progressIndicator);
Where ShowProgress is defined as
void ShowProgress(int value)
{
// Update UI
}
You can read more on IProgress here and here too
Upvotes: 3