Chapter 32. Using File System Classes

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.

Note

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

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

PROPERTY

PURPOSE

AvailableFreeSpace

The total number of bytes available

DriveFormat

The drive format, as in NTFS or FAT32

DriveType

The drive type, as in Fixed or CDRom

IsReady

True if the drive is ready. A drive must be ready before you can use the AvailableFreeSpace, DriveFormat, TotalSize, or VolumeLabel properties.

Name

The drive's name, as in C:

RootDirectory

A DirectoryInfo object representing the drive's root directory

TotalFreeSpace

The number of bytes available, taking quotas into account

TotalSize

The drive's total size, in bytes

VolumeLabel

The drive's label

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:

FIGURE 32-1

Figure 32.1. FIGURE 32-1

' 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

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

Create

Creates a new directory. To use this, make a DirectoryInfo object, passing its constructor the name of the directory to create. Then call the Create method.

CreateSubdirectory

Creates a subdirectory inside this directory

Delete

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 Boolean parameter indicating whether you want to delete all of the directory's files and subdirectories.

GetDirectories

Returns the directory's immediate subdirectories. Optionally, you can include a search string to select particular subdirectories.

GetFiles

Returns the directory's files. Optionally, you can include a search string to select particular files.

MoveTo

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

Attributes

The directory's attributes, such as Compressed, Hidden, or System

CreationTime

The time at which the directory was created on your computer

Exists

Returns True if the directory actually exists

FullName

Gives the directory's fully qualified path

LastAccessTime

The time at which the directory was last accessed

LastWriteTime

The time at which the directory was last written

Name

The directory's name without the path

Parent

A DirectoryInfo representing this directory's parent directory

Root

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

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

CreateDirectory

Creates the directory and any missing directories in its path up to the root

Delete

Deletes a directory

Exists

Returns True if the directory exists

GetCreationTime

Returns the time at which the file was created on your computer

GetDirectories

Returns a directory's subdirectories

GetDirectoryRoot

Returns the directory's root

GetFiles

Returns a directory's files, optionally looking for files matching a pattern

GetLastAccessTime

Returns a directory's last access time

GetLastWriteTime

Returns a directory's last write time

GetParent

Returns a DirectoryInfo representing a directory's parent directory

Move

Moves a file or directory to a new location

SetCreationTime

Sets a directory's creation time

SetLastAccessTime

Sets a directory's last access time

SetLastWriteTime

Sets a directory's last write time

THE FILEINFO CLASS

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.

Table 32.5. TABLE 32-5

METHOD

PURPOSE

CopyTo

Copies the file to a new location

Decrypt

Decrypts a file that was encrypted by the Encrypt method

Delete

Deletes the file

Encrypt

Encrypts the file so it can be read only by the account used to encrypt it

MoveTo

Moves the file to a new location

The FileInfo class also provides some useful properties, summarized in Table 32-6.

Table 32.6. TABLE 32-6

PROPERTY

PURPOSE

Attributes

The file's attributes, such as Compressed, Hidden, or System

CreationTime

The time at which the file was created on your computer

Directory

A DirectoryInfo object for the directory containing the file

Exists

Returns True if the file actually exists

Extension

Returns the file's extension

FullName

Gives the file's fully qualified path

IsReadOnly

Returns True if the file is marked read-only

LastAccessTime

The time at which the file was last accessed on your computer

LastWriteTime

The time at which the file was last written on your computer

Length

The file's size, in bytes

Name

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

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

AppendAllText

Appends a string to the end of a file

Copy

Copies a file to a new file

Create

Creates a file

Decrypt

Decrypts a file that was encrypted by the Encrypt method

Delete

Deletes a file

Encrypt

Encrypts a file so it can be read only by the account used to encrypt it

Exists

Returns True if a file exists

GetAttributes

Returns a file's attributes, such as ReadOnly, System, or Hidden

GetCreationTime

Returns a file's creation time on your computer

GetLastAccessTime

Returns a file's last access time

GetLastWriteTime

Returns a file's last write time

Move

Moves a file to a new location

ReadAllBytes

Returns a file's contents in an array of bytes

ReadAllLines

Returns the lines in a text file as an array of strings

ReadAllText

Returns a text file's contents in a string

SetAttributes

Sets a file's attributes

SetCreationTime

Sets a file's creation time

SetLastAccessTime

Sets a file's last access time

SetLastWriteTime

Sets a file's last write time

WriteAllBytes

Writes a file's contents from an array of bytes

WriteAllLines

Writes a text file's contents from an array of strings

WriteAllText

Writes a text file's contents from a string

THE PATH CLASS

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

ChangeExtension

Changes a filename's extension

Combine

Combines two path strings, adding a backslash between them if needed

GetDirectoryName

Returns the directory name part of a path

GetExtension

Returns the extension part of a filename

GetFileName

Returns the filename part of a file's path

GetFileNameWithoutExtension

Returns the filename part of a file's path without the extension

GetTempFileName

Returns a name for a temporary file

GetTempPath

Returns the path to the system's temporary folder

TRY IT

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.

FIGURE 32-2

Figure 32.2. FIGURE 32-2

Note

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.

Lesson Requirements

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.

Hints

  • 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.

Step-by-Step

  • 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.

    1. 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).

    1. 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.

    1. 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

Note

Please select Lesson 32 on the DVD to view the video that accompanies this lesson.

EXERCISES

  1. 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.

  2. 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.

  3. 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.

Note

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.

EXERCISES
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset