Section 5.3. Copy, Move, and Delete Files


5.3. Copy, Move, and Delete Files

In addition to helping you gather information about the directories and files on your system, the My.Computer.FileSystem object also gives you quick access to a number of methods for performing common file-management tasks, such as copying, moving, and deleting files.


Note: In VB 2005, you can perform common file-management tasks with a single line of code.

5.3.1. How do I do that?

The My.Computer.FileSystem object provides several self-contained methods for performing common file-management operations. They are:

  • CopyFile( ) and CopyDirectory( )

  • MoveFile( ) and MoveDirectory( )

  • RenameFile( ) and RenameDirectory()

  • DeleteFile( ) and DeleteDirectory()

The way you use each of these methods is fairly straightforward. You supply two parameters: a source path and, if required, a target filename or path. For example, you can rename a file with this line of code:

My.Computer.FileSystem.RenameFile("c:\myfile.txt", "newname.txt")

These methods are also available in overloaded versions that give you additional features. We'll take a look at those next.

The move and copy methods of FileSystem are available in a variety of overloaded versions. If you need to overwrite an existing file or directory, be sure to use a version that includes the Boolean parameter overwrite and set it to true. Otherwise, you'll receive an exception and the operation won't be completed. Here's an example of one such option:


Note: In some beta versions, the user interface for moving or deleting a file doesn't appear, even when you choose to see it. However, the underlying task (moving or deleting a file) is always performed correctly.
My.Computer.FileSystem.CopyDirectory("c:\MyFiles", _   "c:\CopyOfMyFiles", True)

Interestingly, among the copying and deleting methods are versions that accept the showUI Boolean parameter. If that parameter is set to TRue, the operation works exactly as if a user had initiated the delete or copy operation in Windows Explorer: dialog boxes appear asking the user to confirm the request to overwrite or delete files, and a progress indicator appears with a Cancel button when a file copy or delete operation is in progress (unless the operation completes very quickly). You can even specify what should happen when the user clicks Cancel (either an exception is thrown or nothing at all happens) using the onUserCancel parameter.

Example 5-3 provides a complete console application that lets you test this behavior.

Example 5-3. Moving and deleting files with Windows UI
Imports System.IO      Module FileManagement          Public Sub Main( )         ' Create a large test file (100 MB).         Dim TestFile As String = "c:\test.bin"         Console.WriteLine("Creating file...")         Dim fs As FileStream = File.OpenWrite(TestFile)         For i As Integer = 1 To 100000000             fs.WriteByte(0)         Next         fs.Close( )              ' Create the target directory.         Console.WriteLine("Creating directory...")         Dim TargetDir As String = "c:\TestDir"         My.Computer.FileSystem.CreateDirectory(TargetDir)         Dim TargetFile As String = Path.Combine(TargetDir, "test.bin")              Console.WriteLine("Moving file...")         ' Try moving the file. Set the following parameters:         '    showUI = UIOption.AllDialogs         ' (Show all the Windows UI, not just error messages.)         '    onUserCancel = UICancelOption.ThrowException         ' (Generate an error if the user clicks Cancel.)         Try             My.Computer.FileSystem.MoveFile(TestFile, TargetFile, _               UIOption.AllDialogs, UICancelOption.ThrowException)             Console.WriteLine("File moved.")         Catch Err As Exception             Console.WriteLine("You canceled the operation.")                  ' Remove the original file.             My.Computer.FileSystem.DeleteFile(TestFile)         End Try              Console.WriteLine("Press Enter to continue.")         Console.ReadLine( )              ' Delete the target directory. Set the following parameters:         '    showUI = UIOption.AllDialogs         ' (Show the confirmation and Windows UI dialog box.)         '    sendToRecycleBin = RecycleOption.SendToRecycleBin         ' (Delete the file permanently.         '    onUserCancel = UICancelOption.DoNothing         ' (Allow the user to cancel this operation.)         My.Computer.FileSystem.DeleteDirectory(TargetDir, _           UIOption.AllDialogs, RecycleOption.SendToRecycleBin, _           UICancelOption.DoNothing)              Console.WriteLine("Cleanup finished.")     End Sub      End Module

As shown in this example, the DeleteFile( ) and DeleteDirectory( ) methods have one additional frill available. By default, when you delete a file, it bypasses the Windows recycle bin. However, you can use an overloaded version of DeleteFile( ) or DeleteDirectory( ) that accepts a sendToRecycleBin parameter. Set this to true to keep your file around as a safeguard.

5.3.2. What about...

...file operations that use special folders? The new My.Computer.FileSystem object allows you to retrieve references to many system-defined folders through the SpecialDirectories class. For example, you can quickly retrieve the path for temporary files, user documents, and the desktop. Here's an example:

Dim Desktop As String = My.Computer.FileSystem.SpecialDirectories.Desktop Console.WriteLine("Your desktop is at: " & Desktop)      Console.Write("It's size is: ") Console.Write(My.Computer.FileSystem.GetDirectoryInfo(Desktop).Size) Console.WriteLine(" bytes") Console.Write("It contains: ") Console.Write(My.Computer.FileSystem.GetFiles(Desktop).Count) Console.WriteLine(" files")

The SpecialDirectories class includes all the following properties, each of which returns a string with the corresponding fully qualified path:

AllUsersApplicationData
CurrentUserApplicationData
Desktop
MyDocuments
MyMusic
MyPictures
Programs
Temp


Visual Basic 2005(c) A Developer's Notebook
Visual Basic 2005: A Developers Notebook
ISBN: 0596007264
EAN: 2147483647
Year: 2006
Pages: 123

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