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.
How do I do that?
The My.Computer.FileSystem
object provides several self-contained methods for performing common
file-management operations. They are:
CopyFile( )
andCopyDirectory( )
MoveFile( )
andMoveDirectory( )
RenameFile( )
andRenameDirectory()
DeleteFile( )
andDeleteDirectory()
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 ...
Get Visual Basic 2005: A Developer's Notebook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.