Read A Text File In Visual Basic

There are many ways to write text or string to a file. In this tutorial, we are going to use StreamReader class.

StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file.


Required Preferences

  • System.Runtime.Extensions.dll for StreamReader class

Procedure

  1. Open the previous project from Write Text To File In Visual Basic Tutorial and rename the project to ReadFileVB or create a new project but it is recommended to use the existing project in the said tutorial.
  2. Once the project is loaded, open the FormMain and add new CommandButton and set the name property to ButtonReadFile and text property to Read File
  3. Double click on to ButtonReadFile to view the code then copy the codes below and paste it to ButtonReadFile_Click event.

  4.  1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    Using OpenFile As New OpenFileDialog

    With OpenFile
    'Create InitialDirectory variable and get the My Documents folder path
    Dim InitialDirectory As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

    'Set the initial directory
    .InitialDirectory = InitialDirectory

    'Set the file extention to filter
    .Filter = "Text files (*.txt)|*.txt;"

    'Set the restore directory
    .RestoreDirectory = True

    If .ShowDialog = DialogResult.OK Then

    Using TextStreamReader As StreamReader = New StreamReader(.FileName)

    TextBoxContainer.Text = TextStreamReader.ReadToEnd()

    TextStreamReader.Close()

    End Using

    Else

    'If Cancel button was click then
    'Do nothing

    End If

    End With

    End Using

  5. Save the project for the future tutorial and run it.
  6. That's all. I hope that you enjoy my tutorials. Subscribe to this page for more.

Comments