Imports System.IO
- This line has to precede the whole program code as it is higher in hierarchy than the StreamReader Class. In Fact, this is the concept of object oriented programming where StreamReader is part of the namespace System.IO.
Now, start a new project and name it in whatever name you wish. Now, insert the OpenFileDialog control into the form because we will use it to read the file from the storage device. The default name of the OpenFileDialog control is OpenFileDialog1, you can use this name or you can rename it with a more meaningful name. The OpenFileDialog control will return a DialogResult value which can determine whether the user clicks the OK button or Cancel button . We will also insert a command button and change its displayed text to 'Open'. It will be used by the user to open and read a certain text file.
It will be the same with saving the file, insert the SaveFileDialog control into the form because we will use it to read the file from the storage device. The SaveFileDialog control will return a DialogResult value which can determine whether the user clicks the OK button or Cancel button . We will also insert a command button and change its displayed text to 'Save'. It will be used by the user to save and write a certain text file.
Next, we insert a textbox and set its Multiline property to true. It is used for displaying the text from a text file. In order to read the text file, we need to create a new instant of the streamReader and connect it to a text file with the following statement:
FileReader = New StreamReader(OpenFileDialog1.FileName)
In addition, we need to use the ReadToEnd method to read the entire text of a text file. The syntax is:
TextBox1.Text = FileReader.ReadToEnd()
Your design will be like this one below:
Now, type the following code below:
Imports System.IO Public Class Form1 Private Sub BtnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOpen.Click Dim FileReader As StreamReader Dim results As DialogResult results = OpenFileDialog1.ShowDialog If results = DialogResult.OK Then FileReader = New StreamReader(OpenFileDialog1.FileName) TextBox1.Text = FileReader.ReadToEnd() End If End Sub Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click Dim FileWriter As StreamWriter Dim results As DialogResult results = SaveFileDialog1.ShowDialog If results = DialogResult.OK Then FileWriter = New StreamWriter(SaveFileDialog1.FileName, False) FileWriter.Write(TextBox1.Text) End If End Sub End Class
Engr. Lyndon R. Bermoy
IT Instructor/System Developer/Android Developer
Mobile: 09079373999
Telephone: 826-9296
E-mail:[email protected]
Visit and like my page on Facebook at: Bermz ISware Solutions
Subscribe at my YouTube Channel at: SerBermz