开发者

Show a Copying-files dialog/form while manually copying files in C#?

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开发者_StackOverflow中文版 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!


There is one built in from the Microsoft.VisualBasic.FileIO Namespace. Don't let the name scare 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);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜