Difference between revisions of "Working with Files in Visual Basic"
(→Detecting a Change to a File) |
m (Text replacement - "<table border="0" cellspacing="0"> " to "<table border="0" cellspacing="0" width="100%">") |
||
(3 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
− | <table border="0" cellspacing="0" width="100%"> | + | <table border="0" cellspacing="0" width="100%"><tr> |
− | <tr> | + | |
<td width="20%">[[Visual Basic and the DataGridView Control|Previous]]<td align="center">[[Visual Basic Essentials|Table of Contents]]<td width="20%" align="right">[[Working with Directories in Visual Basic|Next]]</td> | <td width="20%">[[Visual Basic and the DataGridView Control|Previous]]<td align="center">[[Visual Basic Essentials|Table of Contents]]<td width="20%" align="right">[[Working with Directories in Visual Basic|Next]]</td> | ||
<tr> | <tr> | ||
Line 8: | Line 7: | ||
− | < | + | <htmlet>vbasic</htmlet> |
Line 148: | Line 147: | ||
− | < | + | <htmlet>vbasic</htmlet> |
Latest revision as of 20:15, 27 October 2016
Previous | Table of Contents | Next |
Visual Basic and the DataGridView Control | 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 |
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>
Mode | Description |
---|---|
Append | If the file exists it is opened. Any writes are appended to the end of the file. Requires FileAccess.Write mode |
Create | Creates a new file, removing old file if it already exists |
CreateNew | Creates a new file and returns error if file already exists |
Open | Opens an existing file. Returns error if file does not exist |
OpenOrCreate | If file already exists it is opened, otherwise a new file is created |
Truncate | Opens an existing file and deletes all existing content |
FileAccess Options
Mode | Description |
---|---|
Read | Opens the file for reading only. |
ReadWrite | Opens the file for both reading and writing |
Write | Opens the file to writing only |
Mode | Description |
---|---|
None | The file cannot be opened by any other program until it is closed by the current program |
Read | Other programs may simultaneously open and read from the file, but not write to it. |
ReadWrite | Other programs may simultaneously open and read and write from/to the file. |
Write | Other 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 |