Working with Files in Visual Basic

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Visual Basic and the DataGridView ControlWorking with Directories in Visual Basic


Purchase and download the fully updated Visual Basic 2010 edition of this eBook in PDF and ePub for only $9.99

Buy eBook


In the two previous chapters we looked at accessing databases using Visual Basic. Often, a database provides more complexity and functionality than is needed and sometimes a plain text file is more than enough for storing information. In this chapter, therefore, we will look at how to work with files and directories in Visual Basic.




Opening a Text File in Visual Basic

The first step in working with files in Visual Basic is to open the file. This is achieved using the Visual Basic FileStream class. The FileStream constructor accepts the file name to be opened as the first parameter, followed by a number of other parameters defining the mode in which the file is to be opened. These fall into the categories of FileMode, FileAccess and FileShare. The options available as listed in the following tables:

FileMode Options

<google>ADSDAQBOX_FLOW</google>

ModeDescription
AppendIf the file exists it is opened. Any writes are appended to the end of the file.
Requires FileAccess.Write mode
CreateCreates a new file, removing old file if it already exists
CreateNewCreates a new file and returns error if file already exists
OpenOpens an existing file. Returns error if file does not exist
OpenOrCreateIf file already exists it is opened, otherwise a new file is created
TruncateOpens an existing file and deletes all existing content

FileAccess Options

ModeDescription
ReadOpens the file for reading only.
ReadWriteOpens the file for both reading and writing
WriteOpens the file to writing only

FileShare Options

ModeDescription
NoneThe file cannot be opened by any other program until it is closed by the current program
ReadOther programs may simultaneously open and read from the file, but not write to it.
ReadWriteOther programs may simultaneously open and read and write from/to the file.
WriteOther programs may simultaneously open and write to the file, but not read from it.

With the above options in mind, the following code excerpt opens 'C:\Temp\text.txt' in FileMode.OpenOrCreate with FileAccess.ReadWrite permission and no file sharing, and then closes it:

Dim textFileStream As New IO.FileStream("C:\Temp\test.txt", IO.FileMode.OpenOrCreate,
            IO.FileAccess.ReadWrite, IO.FileShare.None)

textFileStream.Close()

Note that the above code example assumes that the 'C:\Temp' directory already exists. If it does not, the code will fail. Working with Directories is covered in Working with Directories in Visual Basic.

Writing to a File with Visual Basic

Once a file has been opened with the appropriate options, it can be written to using the Visual Basic StreamWriter class. The StreamWriter constructor takes a FileStream as the sole parameter.

The Write() and WriteLine() methods of the StreamWriter class are then used to write to the file. Write() writes the text with no new line appended to the end of each line. WriteLine() on the other hand, appends a new line to end of each line written to the file.

In the following code excerpt a StreamWriter object is created using the FileStream, and a For loop writes 11 lines to the file:

Dim textFileStream As New IO.FileStream("C:\Temp\test.txt", IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite, IO.FileShare.None)
        
Dim myFileWriter As New IO.StreamWriter(textFileStream)
Dim intCounter As Integer

For intCounter = 0 To 10
      myFileWriter.WriteLine("This is line " & CStr(intCounter))
Next intCounter
        
myFileWriter.Close()
textFileStream.Close()

Note that since the act of closing causes the operating system buffers to be flushed to the file, failing to close the Writer and Stream objects before the application exits will result in data written to the file being lost.

Reading From a File in Visual Basic

Now that we have created and written to a file the next step is to read some data from the file. This is achieved using the Visual Basic StreamReader object.

The StreamReader ReadLine() method can be used to read the next line from the file stream including the new line. The Read() method reads a line from the file but removes the new line. The ReadToEnd() method can be used to read from the current line in the file to the end of the file.

The following code excerpt further extends our example to read the data back from the file after it has been written and display the contents in a MessageBox:

        Dim textFileStream As New IO.FileStream("C:\Temp\test.txt", IO.FileMode.OpenOrCreate, 
                       IO.FileAccess.ReadWrite, IO.FileShare.None)
        Dim myFileWriter As New IO.StreamWriter(textFileStream)
        Dim myFileReader As New IO.StreamReader(textFileStream)
        Dim intCounter As Integer
        Dim strFileContents As String

        For intCounter = 0 To 10
            myFileWriter.WriteLine("This is line " & CStr(intCounter))
        Next intCounter

        strFileContents = myFileReader.ReadToEnd()

        MessageBox.Show(strFileContents)

        myFileWriter.Close()
        myFileReader.Close()
        textFileStream.Close()

Detecting a Change to a File

A Visual Basic can monitor a file and receive notification from the operating system when the file is changed by any program. This is achieved using the Visual Basic FileSystemWatcher class.

To try this, start Visual Studio and create a new Windows Application project. Access the Toolbox and double click on the FileSystemWatcher control from the Components section of the list. The new object will appear beneath the Form design area with the name FileSystemWatcher1. Select the object and use the Properties panel to change the Path to C:\Temp and the Filter property to test.txt.

Double click on the FileSystemWatcher1 object to access the event procedure code and modify the changed event as follows:

    Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, 
          ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed

        MessageBox.Show("File changed")

    End Sub

Press F5 to build and run the application and, using Notepad, edit and save the file. As soon as the changes are saved, the "File Changed" MessageBox will appear. Note that the NotifyFilter property can be used to configure which events trigger an notification.

Now that we have covered file handling in Visual Basic the next step is to look at directories in Working with Directories in Visual Basic.


Purchase and download the fully updated Visual Basic 2010 edition of this eBook in PDF and ePub for only $9.99

Buy eBook