Moving, Copying, And Deleting Files


As already mentioned, moving and deleting files or folders is done by the MoveTo() and Delete() methods of the FileInfo and DirectoryInfo classes. The equivalent methods on the File and Directory classes are Move() and Delete(). The FileInfo and File classes also implement the methods CopyTo() and Copy(), respectively. However, no methods exist to copy complete folders — you need to do that by copying each file in the folder.

Use of all these methods is quite intuitive — you can find detailed descriptions in the SDK documentation. This section illustrates their use for the particular cases of calling the static Move(), Copy(), and Delete() methods on the File class. To do this you will build on the previous FileProperties example and call its iteration FilePropertiesAndMovement. This example will have the extra feature that whenever the properties of a file are displayed, the application gives you the option of deleting that file or moving or copying the file to another location.

Example: FilePropertiesAndMovement

Figure 34-4 shows the user interface of the new sample application.

image from book
Figure 34-4

As you can see, FilePropertiesAndMovement is similar in appearance to FileProperties, except for the group of three buttons and a text box at the bottom of the window. These controls are only enabled when the example is actually displaying the properties of a file; at all other times, they are disabled. The existing controls are also squashed up a bit to stop the main form from getting too big. When the properties of a selected file are displayed, FilePropertiesAndMovement automatically places the full pathname of that file in the bottom text box for the user to edit. Users can then click any of the buttons to perform the appropriate operation. When they do, a message box is displayed that confirms the action taken by the user (see Figure 34-5).

image from book
Figure 34-5

When the user clicks the Yes button, the action will be initiated. There are some actions in the form that the user can take that will then cause the display to be incorrect. For instance, if the user moves or deletes a file, you obviously cannot continue to display the contents of that file in the same location. Also, if you change the name of a file in the same folder, your display will also be out of date. In these cases, FilePropertiesAndMovement resets its controls to display only the folder where the file resides after the file operation.

Looking at the Code for FilePropertiesAndMovement

To code this process, you need to add the relevant controls, as well as their event handlers, to the code for the FileProperties example. The new controls are given the names buttonDelete, buttonCopyTo, buttonMoveTo, and textBoxNewPath.

First, look at the event handler that gets called when the user clicks the Delete button:

 protected void OnDeleteButtonClick(object sender, EventArgs e) { try { string filePath = Path.Combine(currentFolderPath, textBoxFileName.Text); string query = "Really delete the file\n" + filePath + "?"; if (MessageBox.Show(query, "Delete File?", MessageBoxButtons.YesNo) == DialogResult.Yes) { File.Delete(filePath); DisplayFolderList(currentFolderPath); } } catch(Exception ex) { MessageBox.Show("Unable to delete file. The following exception" + " occurred:\n" + ex.Message, "Failed"); } } 

The code for this method is contained in a try block because of the obvious risk of an exception being thrown if, for example, you don't have permission to delete the file, or the file is moved by another process after it has been displayed but before the user presses the Delete button. You construct the path of the file to be deleted from the CurrentParentPath field, which contains the path of the parent folder, and the text in the textBoxFileName text box, which contains the name of the file.

The methods to move and copy the file are structured in a very similar manner:

 protected void OnMoveButtonClick(object sender, EventArgs e) { try { string filePath = Path.Combine(currentFolderPath, textBoxFileName.Text); string query = "Really move the file\n" + filePath + "\nto " + textBoxNewPath.Text + "?"; if (MessageBox.Show(query, "Move File?", MessageBoxButtons.YesNo) == DialogResult.Yes) { File.Move(filePath, textBoxNewPath.Text); DisplayFolderList(currentFolderPath); } } catch(Exception ex) { MessageBox.Show("Unable to move file. The following exception" + " occurred:\n" + ex.Message, "Failed"); } } protected void OnCopyButtonClick(object sender, EventArgs e) { try { string filePath = Path.Combine(currentFolderPath, textBoxFileName.Text); string query = "Really copy the file\n" + filePath + "\nto " + textBoxNewPath.Text + "?"; if (MessageBox.Show(query, "Copy File?", MessageBoxButtons.YesNo) == DialogResult.Yes) { File.Copy(filePath, textBoxNewPath.Text); DisplayFolderList(currentFolderPath); } } catch(Exception ex) { MessageBox.Show("Unable to copy file. The following exception" + " occurred:\n" + ex.Message, "Failed"); } } 

You're not quite done yet. You also need to make sure the new buttons and text box are enabled and disabled at the appropriate times. To enable them when you are displaying the contents of a file, you add the following code to DisplayFileInfo():

protected void DisplayFileInfo(string fileFullName) {    FileInfo theFile = new FileInfo(fileFullName);    if (!theFile.Exists)       throw new FileNotFoundException("File not found: " + fileFullName);    textBoxFileName.Text = theFile.Name;    textBoxCreationTime.Text = theFile.CreationTime.ToLongTimeString();    textBoxLastAccessTime.Text = theFile.LastAccessTime.ToLongDateString();    textBoxLastWriteTime.Text = theFile.LastWriteTime.ToLongDateString();    textBoxFileSize.Text = theFile.Length.ToString() + " bytes"; // enable move, copy, delete buttons textBoxNewPath.Text = theFile.FullName; textBoxNewPath.Enabled = true; buttonCopyTo.Enabled = true; buttonDelete.Enabled = true; buttonMoveTo.Enabled = true; }

You also need to make one change to DisplayFolderList:

protected void DisplayFolderList(string folderFullName) {    DirectoryInfo theFolder = new DirectoryInfo(folderFullName);    if (!theFolder.Exists)       throw new DirectoryNotFoundException("Folder not found: " + folderFullName);    ClearAllFields(); DisableMoveFeatures();    textBoxFolder.Text = theFolder.FullName;    currentFolderPath = theFolder.FullName;     // list all subfolders in folder    foreach(DirectoryInfo nextFolder in theFolder.GetDirectories())       listBoxFolders.Items.Add(NextFolder.Name);    // list all files in folder    foreach(FileInfo nextFile in theFolder.GetFiles())       listBoxFiles.Items.Add(NextFile.Name); }

DisableMoveFeatures is a small utility function that disables the new controls:

 void DisableMoveFeatures() { textBoxNewPath.Text = ""; textBoxNewPath.Enabled = false; buttonCopyTo.Enabled = false; buttonDelete.Enabled = false; buttonMoveTo.Enabled = false; } 

You also need to add extra code to ClearAllFields() to clear the extra text box:

protected void ClearAllFields() {    listBoxFolders.Items.Clear();    listBoxFiles.Items.Clear(); textBoxFolder.Text = "";    textBoxFileName.Text = "";    textBoxCreationTime.Text = "";    textBoxLastAccessTime.Text = "";    textBoxLastWriteTime.Text = "";    textBoxFileSize.Text = "";    textBoxNewPath.Text = ""; }

With that, the code is complete.




Professional C# 2005
Pro Visual C++ 2005 for C# Developers
ISBN: 1590596080
EAN: 2147483647
Year: 2005
Pages: 351
Authors: Dean C. Wills

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net