Jaffer Wilson
Jaffer Wilson

Reputation: 7273

How to track the File.Copy() in C#?

I have a very large file in GBs. I am using File.Copy() function in C# win Form (not a WPF).

But the form is hanging as the process if working on the copying of the file. I was looking for a solution that will help me track the progress of the File.Copy(). But I do not want to complicate the progress with customized stuff.

Please suggest me what I can do. I am new to Forms and C#. I hope I will get a solution.

Upvotes: 0

Views: 1748

Answers (3)

D J
D J

Reputation: 937

You can use a BackgroundWorker to accomplish this task.

You can also create your own form and show progress in real-time by this way.

This way, you don't need to use the windows default dialog.

Use these two links for reference. Also, lots of material is available on Google so there shouldn't be any problem.

https://www.youtube.com/watch?v=2qQgctSi4iY

Running a method in BackGroundWorker and Showing ProgressBar

Upvotes: 1

I have an excellent idea. Why can you just use the windows Copy Dialog? Just add a reference:

Microsoft.VisualBasic

And use the code:

try
  {
    FileSystem.CopyFile(source_path, destination_path, UIOption.AllDialogs);
  } 

catch (Exception ext)
   {
      MessageBox.Show(ext.Message);
   }

I guess this will help.

Upvotes: 1

Amadare42
Amadare42

Reputation: 414

Your form hanging, because UI stuff (like updating form content, responding to events, moving window, etc) is executed in main thread (so-called STA thread). In order to not hang UI while executing some operation, you should create another thread for your long-running operation. There are a lot of ways to do it, but the simplest will be to use TPL's Task.Run:

void Click(object sender, EventArgs args) 
{
   Task.Run(CopyFile);
}

void CopyFile() 
{
   File.Copy(this.src, this.target);
   // note that since we're in different thread, we cannot interact with UI,
   // so you have to dispatch your operations to UI thread. That can be done just using 
   // Control's Invoke method
   this.Invoke(NotifySuccess);
}

As for displaying progress, it's will be a bit more complicated. Since File.Copy() doesn't support progress reporting, you have to use FileStreams. You can check example for it here: https://stackoverflow.com/a/6055385/2223729

Upvotes: 2

Related Questions