Show a Copying-files dialog/form while manually co

2019-01-18 05:37发布

I am manually copying some folders and files through C#, and I want to show the user that something is actually going on. Currently, the program looks as if its frozen, but it is actually copying files.

I would think there is already a built-in dialog or form that shows the process, similar to copying/moving files in windows explorer. Is there anything like that available, or will I have to create everything from scratch?

Also, would this be the best method to show the user that something is actively going on?

Thanks for the help!

3条回答
贼婆χ
2楼-- · 2019-01-18 05:48

If you use a BackgroundWorker thread you can show a progress dialog. You will need to use a thread if you don't want to lock the UI.

The example on this MSDN page shows how to update a progress indicator. In this case it's on the main application form, but you can create your own dialog for this.

查看更多
相关推荐>>
3楼-- · 2019-01-18 05:55

There is one built in from the Microsoft.VisualBasic.FileIO Namespace. Don't let the name fool you, it is a very underrated namespace for C#. The static class FileSystem has a CopyFile and CopyDirectory method that has that capability.

FileSystem Members

Pay Close attention to the UIOption in both the CopyFile and CopyDirectory methods. This emulates displays the Windows Explorer copy window.

FileSystem.CopyFile(sourceFile, destinationFile, UIOption.AllDialogs);
FileSystem.CopyDirectory(sourceDirectory, destinationDirectory, UIOption.AllDialogs);
查看更多
放我归山
4楼-- · 2019-01-18 05:55

This depends on the user experience you'd like to provide. You can use Windows APIs to show the standard copy dialog; however, I believe that your application will still seem unresponsive.

I'd recommend something like this:

// WPF
System.Threading.Thread t = new System.Threading.Thread(() =>
{
   foreach(String file in filesToCopy)
    {
        // copy file here

        // WPF UI Update
        Dispatcher.BeginInvoke(() =>
        {
            // progressBar Update
        }); 
    }                    
});

// WinForms
System.Threading.Thread t = new System.Threading.Thread(() =>
{
    foreach(String file in filesToCopy)
    {
        // copy file here

        // WinForms UI Update
        Form1.BeginInvoke(() =>
        {
            // progressBar Update
        }); 
    }               
});

// in either case call
t.Start();

This allows you to use your existing file copy logic, and still provide a nice responsive user interface.

查看更多
登录 后发表回答