Moving, Copying, and Deleting Files

 
Chapter 12 - File and Registry Operations
bySimon Robinsonet al.
Wrox Press 2002
  

We have already mentioned that 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 respectively implement methods, CopyTo() and Copy() . No methods exist to copy complete folders, however - you need to do that by copying each file in the folder.

Use of all these methods is quite intuitive - and you can find full details in MSDN. In this section we are going to illustrate their use for the particular cases of calling the static Move() , Copy() , and Delete() methods on the File class. To do this we will develop our previous FileProperties example into a new example, FilePropertiesAndMovement . This example will have the extra feature that whenever the properties of a file are displayed, the application gives us the option of deleting that file, or moving or copying it to another location.

Example: FilePropertiesAndMovement

The new example looks like this:

click to expand

From this screenshot, we can see that it is very similar in appearance to the FileProperties example, except that there is an additional group of three buttons and a textbox at the bottom of the window. These controls are only enabled when the example is actually displaying the properties of a file - at other times, they are disabled. We've also squashed the existing controls up a bit to stop the main form from getting too big. When the properties of a file are displayed, FilePropertiesAndMovement automatically places the full pathname of that file in the bottom textbox for the user to edit. The user can then click on any of the buttons to perform the appropriate operation. When they do, an appropriate message box is displayed that confirms the action. In the above case, if the user clicks on Copy To we will see this message:

click to expand

Assuming the user confirms the action, it will go ahead. In the case of moving or deleting a file, we obviously can't carry on displaying the contents of that file in the same location. As well as this, if we copy a file to another filename in the same folder, our display will also be out of date. In all of these cases, the example resets its controls to display only the containing folder after the file operation.

To code this up, we need to add the relevant controls, as well as their event handlers to the code for the FileProperties example. We have given the new controls the names buttonDelete , buttonCopyTo , buttonMoveTo , and textBoxNewPath .

We'll look first at the event handler that gets called when the user hits 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, we don't have permission to delete the file, or the file got moved by another process in the time between our example displaying it, and the user hitting the Delete button. We construct the path of the file to be deleted from the CurrentParentPath field, which will contain the path of the parent folder, and the text in the textBoxFileName textbox, which will contain 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");     }     }   

We're not quite done yet. We also need to make sure the new buttons and textbox are enabled and disabled at the appropriate times. To enable them when we are displaying the contents of a file, we 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;   } 

We 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;     }   

We also need to add extra code to ClearAllFields() to clear the extra textbox:

 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#. 2nd Edition
Performance Consulting: A Practical Guide for HR and Learning Professionals
ISBN: 1576754359
EAN: 2147483647
Year: 2002
Pages: 244

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