OPENTEXT, CREATETEXT, AND APPENDTEXT
The File class in the System.IO namespace provides four shared methods that are particularly useful for working with StreamReader and StreamWriter objects associated with text files. The following table summarizes these four methods.
| METHOD | PURPOSE |
| Exists | Returns True if a file with a given path exists. |
| OpenText | Returns a StreamReader that lets you read from an existing text file. |
| CreateText | Creates a new text file, overwriting any existing file at the given path, and returns a StreamWriter that lets you write into the new file. |
| AppendText | If the indicated file does not exist, creates the file. Whether the file is new or previously existing, returns a StreamWriter that lets you append text at the end of the file. |
The OpenCreateAppendText example program lets you open an existing file, create a new file, or append text at the end of an existing file. It uses the following code to demonstrate the Exists and OpenText methods:
Dim file_name As String = Application.StartupPath & "\test.txt"
If Not Exists(file_name) Then
txtData.Text = " < File not found > "
Else
Using sr As StreamReader = OpenText(file_name)
txtData.Text = sr.ReadToEnd()
sr.Close()
End Using
End If
This code uses Exists to see if the file exists. If the file does exist, the code uses OpenText to open the file and get a StreamReader associated with it. It uses the StreamReader class’s ReadToEnd method to display the file’s text in the text box txtData.
The OpenCreateAppendText ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access