Professional Documents
Culture Documents
2015-09-27 CH 5 Edp It
2015-09-27 CH 5 Edp It
27/09/2015
Bale, Robe Ethiopia
6/7/2023 EDP CH5 compiled by ydereje2020@gmail.com 1
5.1. How to open a Text File
‒ To open a text file in VB, you can use the OpenText method. This method opens a specified file and returns a TextStream object that can be used to read from, write to, or
append to the file. Here is an example of how to use this method:
‒ 'Dim MyFile As IO.StreamReader
‒ Dim MyFile As Object
‒ Dim FileName As String
‒ FileName = "D:\\test.txt"
‒ MyFile = IO.File.OpenText(FileName)
‒ RichTextBox1.Text = MyFile.ReadToEnd()
‒ This code opens the file “test.txt” located in the C:\ directory.
Alternatively, you can use the ReadAllText method of the My.Computer.FileSystem object to read the contents of a text file into a string. Here is an example of how to use this method:
‒ Dim myOpenFileDialog As New OpenFileDialog()
‒ myOpenFileDialog.CheckFileExists = True
‒ myOpenFileDialog.DefaultExt = "txt"
‒ myOpenFileDialog.InitialDirectory = "C:\"
‒ myOpenFileDialog.Multiselect = False
‒ If myOpenFileDialog.ShowDialog = DialogResult.OK Then
‒ Me.Text = myOpenFileDialog.FileName
‒ Me.RichTextBox1.Text = My.Computer.FileSystem.ReadAllText(myOpenFileDialog.FileName)
‒ End If
This code reads the contents of the file “test.txt” located in the C:\ directory into a string variable named fileContents.