The System.IO namespace provides several classes for working with the filesystem. The Directory and File classes provide shared methods that you can use to manipulate the filesystem without creating instances of helper objects.
The DirectoryInfo and FileInfo classes let you work with specific relevant filesystem objects. For example, a FileInfo object represents a particular file and provides methods to create, rename, delete, and get information about that file.
The following sections describe these and the other classes that the Framework provides to help you work with the filesystem.
The Directory class provides shared methods for working with directories. These methods let you create, rename, move, and delete directories. They let you enumerate the files and subdirectories within a directory, and get and set directory information such as the directory’s creation and last access time.
The following table describes the Directory class’s shared methods:
METHOD | PURPOSE |
CreateDirectory | Creates a directory and any missing ancestors (parent, grandparent, and so on). |
Delete | Deletes a directory and its contents. It can delete all subdirectories, their subdirectories, and so forth to remove the entire directory tree. |
Exists | Returns True if a path points to an existing directory. |
GetCreationTime | Returns a directory’s creation date and time. |
GetCreationTimeUtc | Returns a directory’s creation date and time in Coordinated Universal Time (UTC). |
GetCurrentDirectory | Returns the application’s current working directory. |
GetDirectories | Returns an array of strings holding the fully qualified names of a directory’s subdirectories. |
GetDirectoryRoot | Returns the directory root for a path (the path need not exist). For example, C:. |
GetFiles | Returns an array of strings holding the fully qualified names of a directory’s files. |
GetFileSystemEntries | Returns an array of strings holding the fully qualified names of a directory’s files and subdirectories. |
GetLastAccessTime | Returns a directory’s last access date and time. |
GetLastAccessTimeUtc | Returns a directory’s last access date and time in UTC. |
GetLastWriteTime | Returns the date and time when a directory was last modified. |
GetLastWriteTimeUtc | Returns the date and time in UTC when a directory was last modified. |
GetLogicalDrives | Returns an array of strings listing the system’s logical drives as in A:. The list only 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. |
GetParent | Returns a DirectoryInfo object representing a directory’s parent. |
Move | Moves a directory and its contents to a new location on the same disk volume. |
SetCreationTime | Sets a directory’s creation date and time. |
SetCreationTimeUtc | Sets a directory’s creation date and time in UTC. |
SetCurrentDirectory | Sets the application’s current working directory. |
SetLastAccessTime | Sets a directory’s last access date and time. |
SetLastAccessTimeUtc | Sets a directory’s last access date and time in UTC. |
SetLastWriteTime | Sets a directory’s last write date and time. |
SetLastWriteTimeUtc | Sets a directory’s last write date and time in UTC. |
The File class provides shared methods for working with files. These methods let you create, rename, move, and delete files. They also make working with file streams a bit easier.
The following table describes the File class’s most useful shared methods:
METHOD | PURPOSE |
AppendAll | Adds text to the end of a file, creating it if it doesn’t exist, and then closes the file. |
AppendText | Opens a file for appending UTF-8 encoded text and returns a StreamWriter class attached to it. |
Copy | Copies a file. |
Create | Creates a new file and returns a FileStream attached to it. |
CreateText | Creates or opens a file for writing UTF-8 encoded text and returns a StreamWriter class attached to it. |
Delete | Permanently deletes a file. |
Exists | Returns True if the specified file exists. |
GetAttributes | Gets a file’s attributes. This is a combination of flags defined by the FileAttributes enumeration: Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContextIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary. |
GetCreationTime | Returns a file’s creation date and time. |
GetCreationTimeUtc | Returns a file’s creation date and time in UTC. |
GetLastAccessTime | Returns a file’s last access date and time. |
GetLastAccessTimeUtc | Returns a file’s last access date and time in UTC. |
GetLastWriteTime | Returns a file’s last write date and time. |
GetLastWriteTimeUtc | Returns a file’s last write date and time in UTC. |
Move | Moves a file to a new location. |
Open | 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. |
OpenRead | Opens a file for reading and returns a FileStream attached to it. |
OpenText | Opens a UTF-8-encoded text file for reading and returns a StreamReader attached to it. |
OpenWrite | Opens a file for writing and returns a FileStream attached to it. |
ReadAllBytes | Returns a file’s contents in an array of bytes. |
ReadAllLines | Returns a file’s lines in an array of strings. |
ReadAllText | Returns a file’s contents in a string. |
Replace | Takes three file paths as parameters, representing a source file, a destination file, and a backup file. If the backup file exists, this method permanently deletes it. It then moves the destination file to the backup file, and moves the source file to the destination file. |
SetAttributes | Sets a file’s attributes. This is a combination of flags defined by the FileAttributes enumeration: Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContextIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary. |
SetCreationTime | Sets a file’s creation date and time. |
SetCreationTimeUtc | Sets a file’s creation date and time in UTC. |
SetLastAccessTime | Sets a file’s last access date and time. |
SetLastAccessTimeUtc | Sets a file’s last access date and time in UTC. |
SetLastWriteTime | Sets a file’s last write date and time. |
SetLastWriteTimeUtc | Sets a file’s last write date and time in UTC. |
WriteAllBytes | Creates or replaces a file, writes an array of bytes into it, and closes the file. |
WriteAllLines | Creates or replaces a file, writes an array of strings into it, and closes the file. |
WriteAllText | 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. Note that some of these properties are available only when the drive is ready, as indicated in the Must Be Ready column. If you try to access them when the drive is not ready, Visual Basic throws an exception. The program should check the IsReady property to determine whether the drive is ready before trying to use the AvailableFreeSpace, DriveFormat, TotalFreeSpace, or VolumeLabel properties.
DRIVEINFO PROPERTY | PURPOSE | MUST BE READY |
AvailableFreeSpace | Returns the amount of free space available on the drive in bytes. | True |
DriveFormat | Returns the name of the filesystem type such as NTFS (NT File System) or FAT32 (32-bit File Allocation Table). (For a comparison of these, see http://www.ntfs.com/ntfs_vs_fat.htm.) | True |
DriveType | Returns a DriveType enumeration value indicating the drive type. This value can be CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, or Unknown. | False |
IsReady | 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. | False |
Name | Return’s the drive’s name. This is the drive’s root name (as in A: or C:). | False |
RootDirectory | Returns a DirectoryInfo object representing the drive’s root directory. See the following section “DirectoryInfo” for more information on this class. | False |
TotalFreeSpace | Returns the total amount of free space on the drive in bytes. | True |
VolumeLabel | Gets or sets the drive’s volume label. | True |
The DriveInfo class also has a public shared method GetDrives that returns an array of DriveInfo objects describing the system’s drives.
A DirectoryInfo object represents a directory. You can use its properties and methods to create and delete directories and to move through a directory hierarchy.
The following table describes the most useful public properties and methods provided by the DirectoryInfo class:
PROPERTY OR METHOD | PURPOSE |
Attributes | Gets or sets flags for the directory from the FileAttributes enumeration: Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary. |
Create | Creates the directory. You can create a DirectoryInfo object, passing its constructor the fully qualified name of a directory that doesn’t exist, and then call the object’s Create method to create the directory. |
CreateSubdirectory | 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 following code creates the Tools subdirectory and the Bin directory inside that: dir_info.CreateSubdirectory("ToolsBin"). |
CreationTime | Gets or sets the directory’s creation time. |
CreationTimeUtc | Gets or sets the directory’s creation time in UTC. |
Delete | Deletes the directory if it is empty. A parameter lets you tell the object to delete its contents, too, if it isn’t empty. |
Exists | Returns True if the directory exists. |
Extension | Returns the extension part of the directory’s name. Normally, this is an empty string for directories. |
FullName | Returns the directory’s fully qualified path. |
GetDirectories | 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. |
GetFiles | 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. |
GetFileSystemInfos | 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. |
LastAccessTime | Gets or sets the directory’s last access time. |
LastAccessTimeUtc | Gets or sets the directory’s last access time in UTC. |
LastWriteTime | Gets or sets the directory’s last write time. |
LastWriteTimeUtc | Gets or sets directory’s last write time in UTC. |
MoveTo | Moves the directory and its contents to a new path. |
Name | The directory’s name without the path information. |
Parent | Returns a DirectoryInfo object, representing the directory’s parent. If the directory is its filesystem’s root (for example, C:), this returns Nothing. |
Refresh | 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. |
Root | Returns a DirectoryInfo object representing the root of the directory’s filesystem. |
ToString | Returns the directory’s fully qualified path and name. |
A FileInfo object represents a file. You can use its properties and methods to create and delete files.
The following table describes the most useful public properties and methods provided by the FileInfo class:
PROPERTY OR METHOD | PURPOSE |
AppendText | Returns a StreamWriter that appends text to the file. |
Attributes | Gets or sets flags for the file from the FileAttributes enumeration: Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary. |
CopyTo | 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 the destination path is relative, it is relative to the application’s current directory, not to the FileInfo object’s directory. |
Create | 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, and then call the Create method to create the file. |
CreateText | 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, and then call the CreateText method to create the file. |
CreationTime | Gets or sets the file’s creation time. |
CreationTimeUtc | Gets or sets the file’s creation time in UTC. |
Delete | Deletes the file. |
Directory | Returns a DirectoryInfo object representing the file’s directory. |
DirectoryName | Returns the name of the file’s directory. |
Exists | Returns True if the file exists. |
Extension | Returns the extension part of the file’s name, including the period. For example, the extension for game.txt is .txt. |
FullName | Returns the file’s fully qualified path and name. |
IsReadOnly | Returns True if the file is marked read-only. |
LastAccessTime | Gets or sets the file’s last access time. |
LastAccessTimeUtc | Gets or sets the file’s last access time in UTC. |
LastWriteTime | Gets or sets the file’s last write time. |
LastWriteTimeUtc | Gets or sets the file’s last write time in UTC. |
Length | Returns the number of bytes in the file. |
MoveTo | 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. |
Name | The file’s name without the path information. |
Open | Opens the file with various 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. |
OpenRead | Returns a read-only FileStream attached to the file. |
OpenText | Returns a StreamReader with UTF-8 encoding attached to the file for reading. |
OpenWrite | Returns a write-only FileStream attached to the file. |
Refresh | 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. |
Replace | 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. |
ToString | Returns the file’s fully qualified name. |
The FileSystemWatcher class keeps an eye on part of the filesystem and raises events to let your program know if something changes. For example, you could make a FileSystemWatcher monitor a work directory. When a new file with a .job extension arrives, the watcher could raise an event and your application could process the file.
The FileSystemWatcher class’s constructor takes parameters that tell it which directory to watch and that give it a filter for selecting files to watch. For example, the filter might be “*.txt” to watch for changes to text files. The default filter is “*.*”, which catches changes to all files that have an extension. Set the filter to the empty string “” to catch changes to all files including those without extensions.
The following table describes the FileSystemWatcher class’s most useful properties:
PROPERTY | PURPOSE |
EnableRaisingEvents | 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. |
Filter | Determines the files for which the watcher reports events. You cannot watch for multiple file types as in *.txt and *.dat. Instead use multiple FileSystemWatcher objects. If you like, you can use AddHandler to make all of the FileSystemWatcher classes use the same event handlers. |
IncludeSubdirectories | Determines whether the object watches subdirectories within the main path. |
InternalBufferSize | Determines the size of the internal buffer. If the watcher is monitoring a very active directory, a small buffer may overflow. |
NotifyFilter | 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. |
Path | Determines the path to watch. |
The FileSystemWatcher class provides only two really useful methods. The first method, Dispose, releases resources used by the component. When you are finished using a watcher, call its Dispose method to allow garbage collection to reclaim its resources more efficiently.
The second method, WaitForChanged, waits for a change synchronously (with an optional timeout). When a change occurs, the method returns a WaitForChangedResult object, giving information about the change that occurred.
When the FileSystemWatcher detects a change asynchronously, it raises an event to let the program know what has happened. The following table describes the class’s events:
NAME | DESCRIPTION |
Changed | A file or subdirectory has changed. |
Created | A file or subdirectory was created. |
Deleted | A file or subdirectory was deleted. |
Error | The watcher’s internal buffer overflowed. |
Renamed | A file or subdirectory was renamed. |
The following simple example shows how to use a FileSystemWatcher to look for new files in a directory:
Private WithEvents JobFileWatcher As FileSystemWatcher
Private Sub Form1_Load() Handles MyBase.Load
Dim watch_path As String =
FileSystem.GetParentPath(Application.StartupPath)
JobFileWatcher = New FileSystemWatcher(watch_path, "*.job")
JobFileWatcher.NotifyFilter = NotifyFilters.FileName
JobFileWatcher.EnableRaisingEvents = True
End Sub
Private Sub JobFileWatcher_Created(sender As Object,
e As FileSystemEventArgs) Handles JobFileWatcher.Created
' Process the new file.
MessageBox.Show("Process new job: " & e.FullPath)
File.Delete(e.FullPath)
End Sub
The program uses the WithEvents keyword to declare a FileSystemWatcher object. When the program’s main form loads, the Form1_Load event handler allocates this object. Its constructor sets the object’s path to the program’s startup directory’s parent. It sets the object’s filter to “*.job” so that the object will watch for changes to files that end with a .job extension.
The event handler sets the watcher’s NotifyFilter to FileName, so it will raise its Created event if a new filename appears in the target directory. Unfortunately, the NotifyFilter values (Attributes, CreationTime, DirectoryName, FileName, LastAccess, LastWrite, Security, and Size) do not match up well with the events provided by the FileSystemWatcher, so you need to figure out which NotifyFilter values to set to raise different kinds of events.
The Form1_Load event handler finishes by setting the watcher’s EnableRaisingEvents property to True so the object starts watching.
When a .job file is created in the watcher’s target directory, the program’s fswJobFiles_Created executes. The program processes and then deletes the file. In this example, the program processes the file by displaying a message giving its fully qualified name. A more realistic example might read the file; parse fields, indicating the type of job this is; assign it to an employee for handling; and then e-mail it to that employee.
The UseFileSystemWatcher example program, which is available for download on the book’s website, uses similar code without the filter to look for any new file in the program’s startup directory.
The Path class provides shared properties and methods that you can use to manipulate paths. Its methods return the path’s filename, extension, directory name, and so forth. Other methods provide values that relate to system-generated paths. For example, they can give you the system’s temporary directory path, or the name of a temporary file.
The following table describes the Path class’s most useful public properties.
PROPERTY | PURPOSE |
AltDirectorySeparatorChar | Returns the alternate character used to separate directory levels in a hierarchical path. Typically this is /. |
DirectorySeparatorChar | Returns the character used to separate directory levels in a hierarchical path. Typically this is (as in C:TestsBilling2008q2.dat). |
InvalidPathChars | Returns a character array that holds characters that are not allowed in a path string. Typically, this array includes characters such as “, <, >, and |, as well as nonprintable characters such as those with ASCII values between 0 and 31. |
PathSeparator | Returns the character used to separate path strings in environment variables. Typically this is a semicolon (;). |
VolumeSeparatorChar | Returns the character placed between a volume letter and the rest of the path. Typically this is a colon (:). |
The following table describes the Path class’s most useful methods.
METHOD | PURPOSE |
ChangeExtension | Changes a path’s extension. |
Combine | Returns two path strings concatenated. |
GetDirectoryName | Returns a path’s directory. |
GetExtension | Returns a path’s extension. |
GetFileName | Returns a path’s filename and extension. |
GetFileNameWithoutExtension | Returns a path’s filename without the extension. |
GetFullPath | Returns a path’s fully qualified value. This can be particularly useful for converting a partially relative path into an absolute path. For example, this statement: Path.GetFullPath("C:TestsOldTestsSoftware....NewCode") returns this result: "C:TestsNewCode" |
GetInvalidFileNameChars | Returns an array listing characters that are invalid in filenames. |
GetInvalidPathChars | Returns an array listing characters that are invalid in file paths. |
GetPathRoot | Returns a path’s root directory string. |
GetRandomFileName | Returns a random filename. |
GetTempFileName | 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 filename might be C:Documents and SettingsRodLocal SettingsTemp mp19D.tmp. |
GetTempPath | Returns the path to the system’s temporary folder. This is the path part of the filenames returned by GetTempFileName. |
HasExtension | Returns True if a path includes an extension. |
IsPathRooted | Returns True if a path is an absolute path. This includes TempWherever and C:ClientsLitigation, but not TempWherever or .Uncle. |