Copy files and folders - UI is unresponsive

Gomo

Member
Joined
Mar 9, 2017
Messages
7
Programming Experience
Beginner
Hello,

part of the program which I'm working on should copy all files and folders from the selected path to the destination path (do a backup). And this the code being used:
C#:
                foreach (string dirPath in Directory.GetDirectories(from_directory, "*", SearchOption.AllDirectories))
                    Directory.CreateDirectory(dirPath.Replace(from_directory, bkpdirectory));

                foreach (string newPath in Directory.GetFiles(from_directory, "*.*", SearchOption.AllDirectories))
                    File.Copy(newPath, newPath.Replace(from_directory, bkpdirectory), true);
It all works fine, but the problem is that my complete UI is unresponsive during the copy process. So my question is, how can I avoid that?
Thanks in advance!
 
Each thread can only do one thing at a time. If the UI thread, i.e. the main thread of your application process, is busy copying files and folders then it can't respond to user input via the UI or refresh what's displayed. This is exactly why long-running tasks like multiple file copies need to be performed on secondary threads. There are a number of ways to accomplish that but, in a WinForms app, one of the most convenient is to use a BackgroundWorker. There are lots of examples around of that. Here's one I prepared earlier:

Using the BackgroundWorker Component
 

Latest posts

Back
Top Bottom