The techniques described in Lesson 31 enable you to read and write text files. They also demonstrate techniques that you'll find useful when you deal with streams other than text files.
Those techniques won't enable you to manipulate the file system itself, however. You can read from or write to a file using them, but not rename a file, move a file to a different directory, or delete a file.
This lesson describes file system classes that make these and other common file manipulation operations easy. In this lesson you learn how to manipulate the file system to rename, move, or delete files and directories. You also learn how to read or write a text file's contents all at once, rather than using a StreamReader
.
These classes are in the System.IO
namespace, so you can make using them in your code easier by including the following directive:
Imports System.IO
The DriveInfo
class provides information about the system's drives. Its static GetDrives
function returns an array of DriveInfo
objects describing all of the system's drives.
Table 32-1 summarizes the DriveInfo
's most useful properties.
Table 32.1. TABLE 32-1
Example program ListDrives (found as part of this lesson's code download and shown in Figure 32-1) uses the following code to describe the system's drives:
' List the available drives. Private Sub Form1_Load() Handles MyBase.Load lstDrives.DataSource = DriveInfo.GetDrives() End Sub ' Display information about the selected drive. Private Sub lstDrives_SelectedIndexChanged() _ Handles lstDrives.SelectedIndexChanged
Dim info As DriveInfo = DirectCast(lstDrives.SelectedItem, DriveInfo) txtName.Text = info.Name txtRoot.Text = info.RootDirectory.FullName txtType.Text = info.DriveType.ToString() txtIsReady.Text = info.IsReady.ToString() ' See if the drive is ready. If (info.IsReady) Then ' Display values. txtLabel.Text = info.VolumeLabel txtTotalSpace.Text = info.TotalSize.ToString() txtTotalFree.Text = info.TotalFreeSpace.ToString() txtAvailableFree.Text = info.AvailableFreeSpace.ToString() txtFormat.Text = info.DriveFormat Else ' Clear values that are unavailable. txtLabel.Clear() txtTotalSpace.Clear() txtTotalFree.Clear() txtAvailableFree.Clear() txtFormat.Clear() End If End Sub
The DirectoryInfo
class provides information about directories. Table 32-2 summarizes useful DirectoryInfo
methods for manipulating directories.
Table 32.2. TABLE 32-2
METHOD | PURPOSE |
---|---|
Creates a new directory. To use this, make a | |
Creates a subdirectory inside this directory | |
Deletes the directory. If you pass no parameters to this method, it only deletes the directory if it is empty. Alternatively, you can pass it a | |
Returns the directory's immediate subdirectories. Optionally, you can include a search string to select particular subdirectories. | |
Returns the directory's files. Optionally, you can include a search string to select particular files. | |
Moves the directory to a new path |
The DirectoryInfo
class also provides a few useful properties, which are summarized in Table 32-3.
Table 32.3. TABLE 32-3
PROPERTY | PURPOSE |
---|---|
The directory's attributes, such as | |
The time at which the directory was created on your computer | |
Returns | |
Gives the directory's fully qualified path | |
The time at which the directory was last accessed | |
The time at which the directory was last written | |
The directory's name without the path | |
A | |
The directory's file system root |
Example program UseDirectoryInfo (found in this lesson's code download) uses a DirectoryInfo
object to display information about directories.
The Directory
class provides shared methods for manipulating directories. For simple tasks these are sometimes easier to use than the comparable DirectoryInfo
class methods because you don't need to create a DirectoryInfo
object to use them. Table 32-4 summarizes the Directory
class's most useful methods.
Table 32.4. TABLE 32-4
METHOD | PURPOSE |
---|---|
Creates the directory and any missing directories in its path up to the root | |
Deletes a directory | |
| Returns |
Returns the time at which the file was created on your computer | |
Returns a directory's subdirectories | |
| Returns the directory's root |
| Returns a directory's files, optionally looking for files matching a pattern |
Returns a directory's last access time | |
Returns a directory's last write time | |
Returns a | |
Moves a file or directory to a new location | |
Sets a directory's creation time | |
Sets a directory's last access time | |
Sets a directory's last write time |
The FileInfo
class, as you can probably guess at this point, provides information about files. Table 32-5 summarizes useful FileInfo
methods for manipulating files.
The FileInfo
class also provides some useful properties, summarized in Table 32-6.
Table 32.6. TABLE 32-6
PROPERTY | PURPOSE |
---|---|
The file's attributes, such as | |
The time at which the file was created on your computer | |
A | |
Returns | |
Returns the file's extension | |
Gives the file's fully qualified path | |
Returns | |
The time at which the file was last accessed on your computer | |
The time at which the file was last written on your computer | |
The file's size, in bytes | |
The file's name without the path |
Example program UseFileInfo (found in this lesson's code download) uses a FileInfo
object to display information about files.
The File
class provides static methods for manipulating files. For simple tasks these are sometimes easier to use than the comparable FileInfo
class methods because you don't need to create a FileInfo
object to use them. The AppendAllText, ReadAllLines, ReadAllText, WriteAllLines
, and WriteAllText
methods are particularly useful for reading and writing text files all at once, although you may still want to use StreamReader
and StreamWriter
if you need to manipulate files one line at a time. Table 32-7 summarizes the File
class's most useful methods.
Table 32.7. TABLE 32-7
METHOD | PURPOSE |
---|---|
Appends a string to the end of a file | |
Copies a file to a new file | |
Creates a file | |
Deletes a file | |
| Encrypts a file so it can be read only by the account used to encrypt it |
Returns | |
Returns a file's attributes, such as | |
Returns a file's creation time on your computer | |
Returns a file's last access time | |
Returns a file's last write time | |
Moves a file to a new location | |
Returns a file's contents in an array of bytes | |
Returns the lines in a text file as an array of strings | |
Returns a text file's contents in a string | |
Sets a file's attributes | |
Sets a file's creation time | |
Sets a file's last access time | |
Sets a file's last write time | |
Writes a file's contents from an array of bytes | |
Writes a text file's contents from an array of strings | |
Writes a text file's contents from a string |
The Path
class provides static methods that perform string operations on file paths. For example, you can use the ChangeExtension
method to change the extension part of a filename. Note that this doesn't affect the file with that name (if there is one); it just manipulates a string holding a filename.
Table 32-8 summarizes the Path
class's most useful methods.
Table 32.8. TABLE 32-8
METHOD | PURPOSE |
---|---|
| Changes a filename's extension |
Combines two path strings, adding a backslash between them if needed | |
Returns the directory name part of a path | |
Returns the extension part of a filename | |
Returns the filename part of a file's path | |
Returns the filename part of a file's path without the extension | |
Returns a name for a temporary file | |
Returns the path to the system's temporary folder |
In this Try It, you build the program shown in Figure 32-2, which enables the user to search for files matching a pattern containing a target string. Enter a directory at which to start the search, select or enter a file pattern in the Pattern combo box, and enter a target string in the Search For textbox. When you click Search, the program searches for files matching the pattern and containing the target string.
You can download the code and resources for this Try It from the book's web page at www.wrox.com
or www.vb-helper.com/24hourvb.html
. You can find them in the Lesson32 folder of the download.
In this lesson:
Start a new project and arrange its form as shown in Figure 32-2.
Give the combo box the options *.vb, *.txt, *.*, and any other patterns that you think would be useful.
Give the form a Load
event handler that places the application's startup path in the Directory textbox (just to have somewhere to start).
Give the Search button a Click
event handler that searches for the desired files.
Use the DirectoryInfo
class's GetFiles
method to search for files matching the pattern.
Use the File
class's ReadAllText
method to get the file's contents. Then use string methods to determine whether the text contains the target string.
To ignore case, convert the target string and the files' contents to lowercase.
Start a new project and arrange its form as shown in Figure 32-2.
Give the combo box the options *.vb, *.txt, *.*, and any other patterns that you think would be useful.
This is reasonably straightforward.
Give the form a Load
event handler that places the application's startup path in the Directory textbox (just to have somewhere to start).
Use code similar to the following:
' Start at the startup directory. Private Sub Form1_Load() Handles MyBase.Load txtDirectory.Text = Application.StartupPath End Sub
Give the Search button a Click
event handler that searches for the desired files.
Use code similar to the following:
' Search for files matching the pattern ' and containing the target string. Private Sub btnSearch_Click() Handles btnSearch.Click lstFiles.Items.Clear() ' Get the file pattern and target string. Dim pattern As String = cboPattern.Text Dim target As String = txtTarget.Text.ToLower() ' Search for files. Dim dirinfo As New DirectoryInfo(txtDirectory.Text) For Each info As FileInfo In dirinfo.GetFiles(pattern, SearchOption.AllDirectories) ' See if we need to look for target text. If target.Length > 0 Then ' If this file contains the target string, ' add it to the list. Dim content As String = File.ReadAllText(info.FullName).ToLower() If (content.Contains(target)) Then _ lstFiles.Items.Add(info) Else ' Just add this file to the list. lstFiles.Items.Add(info) End If Next info End Sub
Please select Lesson 32 on the DVD to view the video that accompanies this lesson.
Copy the Memo program you built in Lesson 31, Exercise 1 (or download Lesson31's version from the book's web site). Modify the program to use the File
class's ReadAllText
and WriteAllText
methods instead of using streams.
Write a program that sorts a text file. Hint: Load the file's lines of text into an array and use Array.Sort
to do the actual sorting. Test the program on the file Names.txt
included in this lesson's download.
Write a program that removes duplicate entries from a text file. Hint: Copy the program you built for Exercise 2. After you sort the array, run through the entries, copying them into a new list. If you see a duplicate entry, skip it and write it to the Immediate window. Test the program on the Names.txt
file included in this lesson's download.
You can find solutions to this lesson's exercises in the Lesson32 folder inside the download available on the book's web site at www.wrox.com
or www.vb-helper.com/24hourvb.html
.