|
|
Title | Quickly read and write the contents of a text file in VB .NET |
Description | |
Keywords | VB.NET, NET, text file, grab, read, write |
Categories | VB.NET, Files and Directories |
|
|
When the program loads, it initializes the file_name variable to point to the text.dat file in the startup directory. In the IDE, this is inside the project directory's bin directory. The program then uses the file name to create a StreamReader. It uses the reader's ReadToEnd method to read the whole file and display it in a TextBox.
When the program closes, it again initializes the file name. This time it uses the name to create a StreamWriter. The second parameter is False indicating that the StreamWriter should not append new text to the file (it replaces the file instead). The program uses the writer's Write method to save the TextBox's current text.
Thanks to Nathon Dalton for suggesting using Finally clauses to ensure that the StreamReader and StreamWriter are closed.
|
|
' Load the file's contents into the TextBox.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
Try
Dim file_name As String = Application.StartupPath() _
& "/text.dat"
Dim stream_reader As New IO.StreamReader(file_name)
Try
txtFileContents.Text = stream_reader.ReadToEnd()
txtFileContents.Select(0, 0)
Finally
stream_reader.Close()
End Try
Catch exc As System.IO.FileNotFoundException
' Ignore this error.
Catch exc As Exception
' Report other errors.
MsgBox(exc.Message, MsgBoxStyle.Exclamation, "Read " & _
"Error")
End Try
End Sub
' Save the current text.
Private Sub Form1_Closing(ByVal sender As Object, ByVal e _
As System.ComponentModel.CancelEventArgs) Handles _
MyBase.Closing
Try
Dim file_name As String = Application.StartupPath() _
& "/text.dat"
Dim stream_writer As New IO.StreamWriter(file_name, _
False)
Try
stream_writer.Write(txtFileContents.Text)
Finally
stream_writer.Close()
End Try
Catch exc As Exception
' Report all errors.
MsgBox(exc.Message, MsgBoxStyle.Exclamation, "Read " & _
"Error")
End Try
End Sub
|
|
|
|
|
|