Visual Basic: Reading and Writing text files
Reading and writing to a text file in visual basic requires the use of the StreamReader and the StreamWriter classes. These are contained in the "System.IO" import file. You can include this file like so:
Imports System.IO
Reading
As it says above, the first line of our code is going to be:
Imports System.IO
As this includes some things we will need. This needs to be put outside any button etc.. events; and right at the top of all the code.
Next we need to create a new StreamReader (in the button code this time):
Dim OurFileReader As StreamReader
Next we will use an open file dialog to see what the user wants to open; and then display whatever the user wants in a textbox for example:
Dim DialogOneResult As DialogResult DialogOneResult = OpenFileDialog1.ShowDialog If DialogOneResult = DialogResult.OK Then OurFileReader = New StreamReader(OpenFileDialog1.FileName) TextBox1.Text = OurFileReader.ReadToEnd() OurFileReader.Close() End If
When we put all the code together it would now display the contents of the text file in the textbox (when the open button was clicked, and a text file was chosen).
Source Code:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim OurFileReader As StreamReader
Dim DialogOneResult As DialogResult
DialogOneResult = OpenFileDialog1.ShowDialog
If DialogOneResult = DialogResult.OK Then
OurFileReader = New StreamReader(OpenFileDialog1.FileName)
TextBox1.Text = OurFileReader.ReadToEnd()
OurFileReader.Close()
End If
End Sub
End Class
Writing
Writing files is a lot like reading them, you start with the same import statement. Then we declare a StreamWriter:
Dim OurFileWriter As StreamWriter
Then we almost do the same thing but this time with a savefiledialog:
Dim SaveDialogResults As DialogResult
SaveDialogResults = SaveFileDialog1.ShowDialog
If SaveDialogResults = DialogResult.OK Then
OurFileWriter = New StreamWriter(SaveFileDialog1.FileName, False)
OurFileWriter.Write(TextBox1.Text)
OurFileWriter.Close()
End If
Putting everything togther you should get something like this:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim OurFileWriter As StreamWriter
Dim SaveDialogResults As DialogResult
SaveDialogResults = SaveFileDialog1.ShowDialog
If SaveDialogResults = DialogResult.OK Then
OurFileWriter = New StreamWriter(SaveFileDialog1.FileName, False)
OurFileWriter.Write(TextBox1.Text)
OurFileWriter.Close()
End If
End Sub
End Class
Back to Visual Basic

