A Visual Basic application can take three basic approaches to file system manipulation: Visual Basic methods, System.IO Framework classes, and the My.Computer.FileSystem namespace. This appendix summarizes the properties, methods, and events provided by these approaches. For more information on file system objects, see Chapter 38, "File-System Objects."
The following table summarizes the Visual Basic methods for working with files. They let a program create, open, read, write, and learn about files.
METHOD | PURPOSE |
---|---|
Method | Purpose |
| Returns True if the file is at the end of file. |
| Closes an open file. |
| Reads data from a file opened in Random and Binary mode into a variable. |
| Reads data as an object from a file opened in Random and Binary mode into a variable. |
| Opens a file for reading or writing. Parameters indicate the mode (Append, Binary, Input, Output, or Random), access type (Read, Write, or ReadWrite), and sharing (Shared, LockRead, LockWrite, or LockReadWrite). |
| Writes data from a variable into a file opened for Random or Binary access. |
| Writes an object from a variable into a file opened for Random or Binary access. |
| Returns a file number that is not currently associated with any file in this application. You should use FreeFile to get file numbers rather than using arbitrary numbers such as 1. |
| Reads data written into a file by the Write method back into a variable. |
| Reads a specific number of characters from the file. |
| Returns the next line of text from the file. |
| Returns the current position within the file. |
| Returns the file's length in bytes. |
| Prints values into the file. Multiple values separated by commas are aligned at tab boundaries. |
| Prints values followed by a new line into the file. Multiple values separated by commas are aligned at tab boundaries. |
| Moves to the indicated position within the file. |
| Writes values into the file, delimited appropriately so that they can later be read by the Input method. |
| Writes values followed by a new line into the file, delimited appropriately so that they can later be read by the Input method. |
The following table describes Visual Basic methods that manipulate directories and files. They let an application list, rename, move, copy, and delete files and directories.
METHOD | PURPOSE |
---|---|
| Changes the application's current working directory. |
| Changes the application's current working drive. |
| Returns the application's current working directory. |
| Returns a file matching a directory path specification that may include wildcards, and matching certain file properties such as ReadOnly, Hidden, or Directory. The first call to Dir should include a path. Subsequent calls can omit the path to fetch the next matching file for the initial path. Dir returns file names without the path and returns Nothing when no more files match. |
Copies a file to a new location. | |
| Returns the date and time when the file was created or last modified. |
| Returns the length of a file in bytes. |
| Returns a value indicating the file's attributes. The value is a combination of the values vbNormal, vbReadOnly, vbHidden, vbSystem, vbDirectory, vbArchive, and vbAlias. |
| Permanently deletes a file. |
| Creates a new directory. |
| Renames a directory or file. |
| Deletes an empty directory. |
| Sets the file's attributes The value is a combination of the values vbNormal, vbReadOnly, vbHidden, vbSystem, vbDirectory, vbArchive, and vbAlias. |
The System.IO namespace provides several classes for working with the file system. The following sections describe the properties, methods, and events provided by these classes.
The FileSystem class provides shared methods for working with the file system at a large scale. The following table describes its most useful properties and methods.
PROPERTY OR METHOD | PURPOSE |
---|---|
| Combines a base path with a relative child path and returns the resulting path. For example, the statement FileSystem.CombinePath("C:SomeplaceLost", "..Else") returns C:SomeplaceElse. |
| Copies a directory and its contents to a new location. A parameter indicates whether you want to overwrite existing files that have the same names. |
| Copies a file to a new location, possibly overwriting an existing file |
| Creates a new directory. |
| Deletes an existing directory. Parameters indicate whether the method should recursively delete the directory's contents and whether the deleted files should be placed in the Recycle Bin or deleted permanently. |
| Deletes a file. A parameter indicates whether the file should be placed in the Recycle Bin or deleted permanently. |
| Returns True if the specified directory exists. |
| Returns True if the specified file exists. |
| Returns a collection holding names of files that contain a search string. |
| Returns a read-only collection of strings giving the subdirectories within a specific directory. Parameters indicate whether the method should recursively search the subdirectories and whether the routine should allow wildcards. |
| Returns a DirectoryInfo object representing a directory. Note that the directory need not exist yet. For example, you can create a DirectoryInfo object and then use its Create method to create the directory. |
| Returns a DriveInfo object representing a drive. |
| Returns a FileInfo object representing a file. Note that the file need not exist yet. For example, you can create a FileInfo object and then use its Create method to create the file. |
| Returns a read-only collection of strings giving the names of files within a specific directory. Parameters indicate whether the method should recursively search the subdirectories and whether the routine should allow wildcards. |
| Returns the name portion of a file path. |
| Returns a directory's parent directory path. |
| Creates a uniquely named empty file and returns its full path. |
| Moves a directory to a new parent directory. A parameter indicates whether you want to overwrite existing files with the same names. |
| Moves a file to a new directory. Parameters indicate whether the file should overwrite an existing file at the new location. |
| Returns a TextFieldParser for a file. A TextFieldParser makes it easy to read fields from a delimited file or from a file with fixed-width field columns. |
| Returns a StreamReader attached to a file. |
| Returns a StreamWriter attached to a file. A parameter indicates whether the StreamWriter should append to the file or create a new file. |
| Returns a file's contents as an array of bytes. |
Returns a file's contents as a string. | |
| Changes a directory's name within its current parent directory. |
| Changes a file's name within its current directory. |
| Writes a byte array into a file. A parameter indicates whether the method should append the bytes to the file or create a new file. |
| Writes a string into a file. A parameter indicates whether the method should append the string to the file or create a new file. |
The Directory class provides shared methods for working with directories. The following table summarizes its shared methods.
METHOD | PURPOSE |
---|---|
| Creates all of the directories along a path. |
| Deletes a directory and its contents. It can recursively delete all subdirectories. |
| Returns True if the path points to an existing directory. |
| Returns a directory's creation date and time. |
| Returns a directory's creation date and time in Coordinated Universal Time (UTC). |
| Returns the application's current working directory. |
| Returns an array of strings holding the fully qualified names of a directory's subdirectories. |
| Returns the directory root for a path, which need not exist (for example, C:). |
| Returns an array of strings holding the fully qualified names of a directory's files. |
| Returns an array of strings holding the fully qualified names of a directory's files and subdirectories. |
| Returns a directory's last access date and time. |
| Returns a directory's last access date and time in UTC. |
| Returns the date and time when a directory was last modified. |
| Returns the date and time when a directory was last modified in UTC. |
| Returns an array of strings listing the system's logical drives as in A:. The list includes drives that are attached. For example, it lists an empty floppy drive and a connected flash disk but doesn't list a flash disk after you disconnect it. |
| Returns a DirectoryInfo object representing a directory's parent directory. |
| Moves a directory and its contents to a new location on the same disk volume. |
| Sets a directory's creation date and time. |
| Sets a directory's creation date and time in UTC. |
| Sets the application's current working directory. |
| Sets a directory's last access date and time. |
| Sets a directory's last access date and time in UTC. |
| Sets a directory's last write date and time. |
| Sets a directory's last write date and time in UTC. |
The File class provides shared methods for working with files. The following table summarizes its most useful shared methods.
METHOD | PURPOSE |
---|---|
| Adds text to the end of a file, creating it if it doesn't exist, and then closes the file. |
| Opens a file for appending UTF-8 encoded text and returns a StreamWriter attached to it. (For more information on UTF-8, see |
| Copies a file. |
| Creates a new file and returns a FileStream attached to it. |
| Creates or opens a file for writing UTF-8 encoded text and returns a StreamWriter attached to it. |
| Permanently deletes a file. |
| Returns True if the specified file exists. |
| Gets a file's attributes. This is a combination of flags defined by the FileAttributes enumeration, which defines the values Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContextIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary. |
| Returns a file's creation date and time. |
| Returns a file's creation date and time in UTC. |
| Returns a file's last access date and time. |
| Returns a file's last access date and time in UTC. |
| Returns a file's last write date and time. |
| Returns a file's last write date and time in UTC. |
| Moves a file to a new location. |
| Opens a file and returns a FileStream attached to it. Parameters let you specify the mode (Append, Create, CreateNew, Open, OpenOrCreate, or Truncate), access (Read, Write, or ReadWrite), and sharing (Read, Write, ReadWrite, or None) settings. |
| Opens a file for reading and returns a FileStream attached to it. |
| Opens a UTF-8 encoded text file for reading and returns a StreamReader attached to it. |
| Opens a file for writing and returns a FileStream attached to it. |
| Returns a file's contents in an array of bytes. |
| Returns a file's lines in an array of strings. |
| Returns a file's contents in a string. |
| This method takes three file paths as parameters representing a source file, a destination file, and a backup file. If the backup file exists, the method permanently deletes it. It then moves the destination file to the backup file, and moves the source file to the destination file. For example, imagine a program that writes a log file every time it runs. It could use this method to keep three versions of the log: the current log (the method's source file), the most recent backup (the method's destination file), and a second backup (the method's backup file). This method throws an error if either the source or destination file doesn't exist. |
| Sets a file's attributes. This is a combination of flags defined by the FileAttributes enumeration, which defines the values Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContextIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary. |
| Sets a file's creation date and time. |
| Sets a file's creation date and time in UTC. |
| Sets a file's last access date and time. |
| Sets a file's last access date and time in UTC. |
| Sets a file's last write date and time. |
| Sets a file's last write date and time in UTC. |
| Creates or replaces a file, writes an array of bytes into it, and closes the file. |
| Creates or replaces a file, writes an array of strings into it, and closes the file. |
| Creates or replaces a file, writes a string into it, and closes the file. |
A DriveInfo object represents one of the computer's drives. The following table describes the properties provided by this class. The final column in the table indicates whether a drive must be ready for the property to work without throwing an exception. Use the IsReady property to see whether the drive is ready before using those properties.
PROPERTY | PURPOSE | MUST BE READY? |
---|---|---|
Returns the amount of free space available on the drive in bytes. This value takes quotas into account, so it may not match TotalFreeSpace. |
| |
| Returns the name of the file system type such as NTFS or FAT32. (For more information on NTFS and FAT file systems, search the Web. For example, the page |
|
| Returns a DriveType enumeration value indicating the drive type. This value can be CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, or Unknown. |
|
| Returns True if the drive is ready. Many DriveInfo properties are unavailable and raise exceptions if you try to access them while the drive is not ready. |
|
| Return's the drive's name. This is the drive's root name as in A: or C:. |
|
| Returns a DirectoryInfo object representing the drive's root directory. See the section "DirectoryInfo" later in this appendix for more information. |
|
| Returns the total amount of free space on the drive in bytes. |
|
| Returns the total amount of space on the drive in bytes. |
|
| Gets or sets the drive's volume label. |
|
A DirectoryInfo object represents a directory. The following table summarizes its most useful properties and methods.
PROPERTY OR METHOD | PURPOSE |
---|---|
| Gets or sets flags from the FileAttributes enumeration for the directory. These flags can include Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary. |
| Creates the directory. You can create a DirectoryInfo object, passing its constructor the fully qualified name of a directory that doesn't exist. You can then call the object's Create method to create the directory. |
| Creates a subdirectory within the directory and returns a DirectoryInfo object representing it. The subdirectory's path must be relative to the DirectoryInfo object's directory but can contain intermediate subdirectories. For example, the statement |
| Gets or sets the directory's creation time. |
| Gets or sets the directory's creation time in UTC. |
| Deletes the directory if it is empty. A parameter lets you tell the object to delete its contents, too, if it isn't empty. |
| Returns True if the directory exists. |
| Returns the extension part of the directory's name. Normally, this is an empty string for directories. |
| Returns the directory's fully qualified path. |
| Returns an array of DirectoryInfo objects representing the directory's subdirectories. An optional parameter gives a pattern to match. This method does not recursively search the subdirectories. |
| Returns an array of FileInfo objects representing files inside the directory. An optional parameter gives a pattern to match. This method does not recursively search subdirectories. |
| Returns a strongly typed array of FileSystemInfo objects representing subdirectories and files inside the directory. The items in the array are DirectoryInfo and FileInfo objects, both of which inherit from FileSystemInfo. An optional parameter gives a pattern to match. This method does not recursively search subdirectories. |
| Gets or sets the directory's last access time. |
| Gets or sets the directory's last access time in UTC. |
| Gets or sets the directory's last write time. |
| Gets or sets the directory's last write time in UTC. |
| Moves the directory and its contents to a new path. |
| Returns the directory's name without the path information. |
| Returns a DirectoryInfo object representing the directory's parent. If the directory is its file system's root (for example, C:), this returns Nothing. |
| Refreshes the DirectoryInfo object's data. For example, if the directory has been accessed since the object was created, you must call Refresh to load the new LastAccessTime value. |
| Returns a DirectoryInfo object representing the root of the directory's file system. |
| Returns the directory's fully qualified path and name. |
A FileInfo object represents a file. The following table summarizes its most useful properties and methods.
Property or Method | Purpose |
---|---|
| Returns a StreamWriter that appends text to the file. |
| Gets or sets flags from the FileAttributes enumeration for the file. These flags can include Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary. |
| Copies the file and returns a FileInfo object representing the new file. A parameter lets you indicate whether the copy should overwrite an existing file if it already exists. If the destination path is relative, it is relative to the application's current directory, not to the FileInfo object's directory. |
| Creates the file and returns a FileStream object attached to it. For example, you can create a FileInfo object passing its constructor the name of a file that doesn't exist. Then you can call the Create method to create the file. |
| Creates the file and returns a StreamWriter attached to it. For example, you can create a FileInfo object passing its constructor the name of a file that doesn't exist. Then you can call the CreateText method to create the file. |
| Gets or sets the file's creation time. |
| Gets or sets the file's creation time in UTC. |
| Deletes the file. |
| Returns a DirectoryInfo object representing the file's directory. |
| Returns the name of the file's directory. |
| Returns True if the file exists. |
| Returns the extension part of the file's name including the period. For example, the extension for game.txt is .txt. |
| Returns the file's fully qualified path and name. |
| Returns True if the file is marked read-only. |
| Gets or sets the file's last access time. |
| Gets or sets the file's last access time in UTC. |
| Gets or sets the file's last write time. |
| Gets or sets the file's last write time in UTC. |
| Returns the number of bytes in the file. |
| Moves the file to a new location. If the destination uses a relative path, it is relative to the application's current directory, not to the FileInfo object's directory. When this method finishes, the FileInfo object is updated to refer to the file's new location. |
| The file's name without the path information. |
| Opens the file with different mode (Append, Create, CreateNew, Open, OpenOrCreate, or Truncate), access (Read, Write, or ReadWrite), and sharing (Read, Write, ReadWrite, or None) settings. This method returns a FileStream object attached to the file. |
| Returns a read-only FileStream attached to the file. |
| Returns a StreamReader with UTF-8 encoding attached to the file for reading. |
| Returns a write-only FileStream attached to the file. |
| Refreshes the FileInfo object's data. For example, if the file has been accessed since the object was created, you must call Refresh to load the new LastAccessTime value. |
| Replaces a target file with this one, renaming the old target as a backup copy. If the backup file already exists, it is deleted and replaced with the target. You can use this method to save backups of logs and other periodically updated files. |
| Returns the file's fully qualified name. |
The FileSystemWatcher class lets an application watch for changes to a file or directory. The following table summarizes its most useful properties.
PROPERTY | PURPOSE |
---|---|
| Determines whether the component is enabled. Note that this property is False by default, so the watcher will not raise any events until you set it to True. |
| Determines the files for which the watcher reports events. You cannot watch for multiple file types as in *.txt and *.dat. Instead, use multiple FileSystemWatchers. If you like, you can use AddHandler to make all of the FileSystemWatchers use the same event handlers. |
| Determines whether the object watches subdirectories within the main path. |
| Determines the size of the internal buffer. If the watcher is monitoring a very active directory, a small buffer may overflow. |
| Determines the types of changes that the watcher reports. This is a combination of values defined by the NotifyFilters enumeration and can include the values Attributes, CreationTime, DirectoryName, FileName, LastAccess, LastWrite, Security, and Size. |
| Determines the path to watch. |
The following table summarizes the FileSystemWatcher class's two most useful methods.
METHOD | PURPOSE |
---|---|
| Releases resources used by the object. |
| Synchronously waits for a change to the target file or directory. |
The following table summarizes the class's events.
NAME | DESCRIPTION |
---|---|
| A file or subdirectory has changed. |
| A file or subdirectory was created. |
| A file or subdirectory was deleted. |
| The watcher's internal buffer overflowed. |
| A file or subdirectory was renamed. |
The Path class provides shared properties and methods that you can use to manipulate paths. The following table summarizes its most useful public properties.
PROPERTY | PURPOSE |
---|---|
| Returns the alternate character used to separate directory levels in a hierarchical path (typically, /). |
| Returns the character used to separate directory levels in a hierarchical path (typically, , as in |
| Returns a character array that holds characters that are not allowed in a path string. Typically, this array will include characters such as ", <, >, and |, as well as nonprintable characters such as those with ASCII values between 0 and 31. |
| Returns the character used to separate path strings in environment variables (typically, ;). |
| Returns the character placed between a volume letter and the rest of the path (typically, :, as in |
The following table summarizes the Path class's most useful methods.
METHOD | PURPOSE |
---|---|
| Changes a path's extension. |
| Returns two path strings concatenated. This does not simplify the result as the FileSystem.CombinePath method does. |
| Returns a path's directory. |
| Returns a path's extension. |
| Returns a path's file name and extension. |
| Returns a path's file name without the extension. |
| Returns a path's fully qualified value. This can be particularly useful for converting a partially relative path into an absolute path. For example, the statement |
| Returns a character array that holds characters that are not allowed in a file names. |
| Returns a path's root directory string. For example, the statement |
| Returns a random file name. |
| Creates a uniquely named, empty temporary file, and returns its fully qualified path. Your program can open that file for scratch space, do whatever it needs to do, close the file, and then delete it. A typical file name might be "C:Documents and SettingsRodLocal SettingsTemp mp19D.tmp." |
| Returns the path to the system's temporary folder. This is the path part of the file name returned by GetTempFileName. |
| Returns True if a path includes an extension. |
| Returns True if a path is an absolute path. This includes TempWherever and C:ClientsLitigation, but not TempWherever or ..Uncle. |
The My.Computer.FileSystem object provides tools for working with drives, directories, and files. The following table summarizes this object's properties.
PROPERTY | DESCRIPTION |
---|---|
| Gets or sets the fully qualified path to the application's current directory. |
| Returns a read-only collection of DriveInfo objects describing the system's drives. See Chapter 38, "File-System Objects," for information about the DriveInfo class. |
| Returns a SpecialDirectoriesProxy object that has properties giving the locations of various special directories such as the system's temporary directory and the user's My Documents directory. See the section "My.Computer.FileSystem.SpecialDirectories" later in this appendix for more information. |
The following list summarizes the My.Computer.FileSystem object's methods:
METHOD | PURPOSE |
---|---|
| Combines a base path with a relative path reference and returns a properly formatted fully qualified path. |
| Copies a directory. Parameters indicate whether to overwrite existing files, whether to display a progress indicator, and what to do if the user presses Cancel during the operation. |
| Copies a file. Parameters indicate whether to overwrite existing files, whether to display a progress indicator, and what to do if the user presses Cancel during the operation. |
| Creates all of the directories along a path. |
| Deletes a directory. Parameters indicate whether to recursively delete subdirectories, prompt the user for confirmation, or move the directory into the Recycle Bin. |
| Deletes a file. Parameters indicate whether to prompt the user for confirmation, or move the file into the Recycle Bin, and what to do if the user presses Cancel while the deletion is in progress. |
| Returns True if a specified directory exists. |
| Returns True if a specified file exists. |
| Returns a collection holding names of files that contain a search string. |
| Returns a string collection listing subdirectories of a given directory. Parameters tell whether to recursively search the subdirectories, and wildcards to match. |
| Returns a DirectoryInfo object for a directory. See the section "DirectoryInfo" earlier in this appendix for more information. |
| Returns a DriveInfo object for a drive. See the section "DriveInfo" earlier in this appendix for more information. |
| Returns a FileInfo object for a file. See the section "FileInfo" earlier in this appendix for more information. |
| Returns a string collection holding the names of files within a directory. Parameters indicate whether the search should recursively search subdirectories and give wildcards to match. |
| Returns the fully qualified path of a path's parent. For example, this returns a file's or directory's parent directory. |
| Moves a directory. Parameters indicate whether to overwrite files that have the same name in the destination directory and whether to prompt the user when such a collision occurs. |
| Moves a file. Parameters indicate whether to overwrite a file that has the same name as the file's destination and whether to prompt the user when such a collision occurs. |
| Opens a TextFieldParser object attached to a delimited or fixed-field file (such as a log file). You can use the object to parse the file. |
| Opens a StreamReader object attached to a file. You can use the object to read the file. |
| Opens a StreamReader object attached to a file. You can use the object to write into the file. |
| Reads all the bytes from a binary file into an array. |
| Reads all the text from a text file into a string. |
| Renames a directory within its parent directory. |
| Renames a file with its directory. |
| Writes an array of bytes into a binary file. A parameter tells whether to append the data or rewrite the file. |
| Writes a string into a text file. A parameter tells whether to append the string or rewrite the file. |
The My.Computer.FileSystem.SpecialDirectories property returns a SpecialDirectoriesProxy object that has properties giving the locations of various special directories (such as the system's temporary directory and the user's My Documents directory). The following table summarizes these special directory properties.
PROPERTY | PURPOSE |
---|---|
| The directory where applications should store settings for all users (typically, something like C:ProgramDataWindowsApplication1WindowsApplication11.0.0.0). |
| The directory where applications should store settings for the current user (typically, something like C:UsersCrazyBobAppDataRoamingWindowsApplication1WindowsApplication11.0.0.0). |
| The current user's desktop directory (typically, C:UsersCrazyBobDesktop). |
| The current user's My Documents directory (typically, C:UsersCrazyBobDocuments). |
| The current user's My Music directory (typically, C:UsersCrazyBobMusic). |
| The current user's My Pictures directory (typically, C:UsersCrazyBobPictures). |
| The Program Files directory (typically, C:Program Files). |
| The current user's Programs directory (typically, C:UsersCrazyBobAppDataRoamingMicrosoftWindowsStart MenuPrograms). |
| The current user's temporary directory (typically, C:UsersCrazyBobAppDataLocalTemp). |