Programming C#, 4th Edition by Jesse Liberty

Programming C#, 4th Edition by Jesse Liberty

Author:Jesse Liberty [Jesse Liberty]
Language: eng
Format: epub
Tags: COMPUTERS / Programming Languages / C#
ISBN: 9780596552725
Publisher: O'Reilly Media
Published: 2009-02-08T16:00:00+00:00


Tip

Because this is the only use of the compare method, it is reasonable to put this special knowledge that the sort is from big to small right into the compare method itself. The alternative is to sort small to big, and have the calling method reverse the results, as you saw in Example 12-1.

To test the length of the FileInfo object, you must cast the Object parameters to FileInfo objects (which is safe because you know this method will never receive anything else):

if (file1.Length > file2.Length) { return -1; } if (file1.Length < file2.Length) { return 1; } return 0; } }

Returning to GetFileList( ), you were about to instantiate the IComparer reference and pass it to the Sort( ) method of fileList:

IComparer<FileInfo> comparer = ( IComparer<FileInfo> ) new FileComparer(); fileList.Sort(comparer);

That done, you can return fileList to the calling method:

return fileList;

The calling method was btnCopy_Click. Remember, you went off to GetFileList( ) in the first line of the event handler!

protected void btnCopy_Click (object sender, System.EventArgs e) {List<FileInfo> fileList = GetFileList();

At this point, you've returned with a sorted list of File objects, each representing a file selected in the source TreeView.

You can now iterate through the list, copying the files and updating the UI:

foreach (FileInfo file in fileList) { try { lblStatus.Text = "Copying " + txtTargetDir.Text + "\\" + file.Name + "..."; Application.DoEvents( ); file.CopyTo(txtTargetDir.Text + "\\" + file.Name,chkOverwrite.Checked); } catch (Exception ex) { MessageBox.Show(ex.Message); } } lblStatus.Text = "Done.";

As you go, write the progress to the lblStatus label and call Application.DoEvents( ) to give the UI an opportunity to redraw. Then call CopyTo( ) on the file, passing in the target directory obtained from the text field, and a Boolean flag indicating whether the file should be overwritten if it already exists.

You'll notice that the flag you pass in is the value of the chkOverWrite checkbox. The Checked property evaluates true if the checkbox is checked and false if not.

The copy is wrapped in a try block because you can anticipate any number of things going wrong when copying files. For now, handle all exceptions by popping up a dialog box with the error; you might want to take corrective action in a commercial application.

That's it; you've implemented file copying!



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.