The System.IO.File namespace provides four 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 following code demonstrates the Exists and OpenText methods. First, it 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 the file. It uses the StreamReader class’s ReadToEnd method to display the file’s text in the program text box txtData.
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
The following code demonstrates the CreateText method. The code uses CreateText to create a new text file named test.txt. If test.txt already exists, CreateText overwrites it without warning. The program uses the StreamWriter returned by CreateText to write the contents of the txtData text box into the file and closes the file.
Dim file_name As String = Application.StartupPath & "\test.txt" Using sw As StreamWriter = CreateText(file_name) sw.Write(txtData.Text) sw.Close() End Using
The following code demonstrates the AppendText method. The AppendText method creates the file if it doesn’t already exist, or opens it for appending if it does exist. The program uses the StreamWriter returned by AppendText to write into the file and then closes the file.
Dim file_name As String = Application.StartupPath & "\test.txt" Using sw As StreamWriter = AppendText(file_name) sw.Write(txtData.Text) sw.Close() End Using