Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Section A.15. Chapter 15: Accessing Folders and Files

A.15. Chapter 15: Accessing Folders and Files

Handle Files with the My object.

The simplest method of saving data to a file is to call one of the WriteAllBytes or WriteAllText methods of the My.Computer.FileSystem object. You can also use the IO namespace to set up a Writer object to send data to a file, and a Reader object to read data from the file.

Master It

Show the statements that save a TextBox control's contents to a file and the statements that reload the same control from the data file. Use the My.Computer.FileSystem component.


The following statement saves the control's Text property to a file whose path is stored in the filename variable. Prompt users with the Open dialog box control for the path of the file and use it in your code.

My.Computer.FileSystem.WriteAllText( _
       fileName, TextBox1.Text, True)

To read the data back and place it in the TextBox1 control again, use the following statement:

TextBox1.Text = My.Computer.FileSystem.ReadAllText(fileName)

Write data to a file with the IO namespace

To send data to a file you must set up a FileStream object, which is a channel between the application and the file. To send data to a file, create a StreamWriter or BinaryWriter object on the appropriate FileStream object. Likewise, to read from a file, create a StreamReader or BinaryReader on the appropriate FileStream object. To send data to a file, use the Write and WriteString methods of the appropriate StreamWriter object. To read data from the file, use the Read, ReadBlock, ReadLine, and ReadToEnd methods of the StreamReader object.

Master It

Write the contents of a TextBox control to a file using the methods of the IO namespace.


Begin by setting up a FileStream object to connect your application to a data file. Then create a StreamWriter object on top of the FileStream object and use the Write method to send data to the file:

Dim FS As FileStream
FS = New FileStream(fileName, FileMode.Create)
Dim SW As StreamWriter(FS)

To read the data back and reload the TextBox control, set up an identical FileStream object, then create a StreamReader object on top of it, and finally call the ReadToEnd method:

Dim FS As New FileStream(fileName, _
        System.IO.FileMode.OpenOrCreate, _
Dim SR As New StreamReader(FS)

TextBox1.Text = SR.ReadToEnd()

Manipulate folders and files.

The IO namespace provides the Directory and File classes, which represent the corresponding entities. Both classes expose a large number of methods for manipulating folders (CreateDirectory, Delete, GetFiles, and so on) and files (Create, Delete, Copy, OpenRead, and so on).

Master It

How will you retrieve the attributes of a drive, folder, and file using the IO namespace's classes?


Start by creating DriveInfo, DirectoryInfo, and FileInfo files. Specify the path of the corresponding entity in the class's constructor:

Dim DrvInfo As New DriveInfo("C:\")
Dim DirInfo As New DirectoryInfo( _
       "C:\Program Files")
Dim FInfo As New FileInfo( _
      "C:\Program Files\My Apps\Readme.txt")

Then enter the name of one of these objects, followed by a period, and select the appropriate property from the IntelliSense list.

The available space on drive C: is given by the property DrvInfo.AvailableFreeSpace, and its type is given by the property DrvInfo.DriveType.ToString. The attributes of the folder Program Files are given by the property DirInfo.Attributes. The size of the Readme.txt file in the same folder is given by the property FInfo.Length.

The DrvInfo, DirInfo, and FInfo objects also expose methods for manipulating the corresponding entities. The method GetDrives of the DriveInfo class returns the names of all drives on the target computer. To manipulate a folder, use one of the Delete, Create, MoveTo, or other methods of the DirInfo class. Finally, to manipulate a file, use one of the Delete, Encrypt, Decrypt, Open, or other methods of the FInfo class.

Monitor changes in the file system and react to them.

The FileSystemWatcher is a special component that allows your application to monitor changes in the file system. You can specify the types of changes you want to monitor by using the NotifyFilter property, the types of files you want to monitor by using the Filter property, and the path you want to monitor by using the Path property. The FileSystemWatcher component fires the Changed, Created, Deleted, and Renamed events, depending on the type of change(s) you specified. Once activated, the FileSystemWatcher component fires an event every time one of the specified items changes.

Master It

Assume that an application running on a remote computer creates a file in the E:\Downloaded\Orders folder for each new order. How will you set up a FileSystemWatcher component to monitor this folder and notify your application about the arrival of each new order?


First, drop an instance of the FileSystemWatcher component on your form and insert the following statements in the form's Load event handler to set up and activate the FileSystemWatcher component:

FileSystemWatcher1.Path = "E:\Downloaded\Orders"
FileSystemWatcher1.IncludeSubdirectories = False

FileSystemWatcher1.Filter = "*.txt"
FileSystemWatcher1.NotifyFilter = _
FileSystemWatcher1.EnableRaisingEvents = True

Then enter some code in the FileSystemWatcher component's Created event handler:

Private Sub WatcherHandler( _
           ByVal sender As Object, _
           ByVal e As System.IO.FileSystemEventArgs) _
           Handles FileSystemWatcher1.Created, _
   MsgBox("File " & e.FullPath & " arrived!"
End Sub

You can use any of the methods of the My.Computer.FileSystem or the IO namespace to handle the new file, which is given by the property FullPath of the handler's FileSystemEventArgs argument.


You are currently reading a PREVIEW of this book.


Get instant access to over $1 million worth of books and videos.


Start a Free 10-Day Trial

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint