Wednesday, February 27, 2013

Read a text file

Read a text file

Reading a text file is the question most often asked because it is still relevant. Here, we present the reading of a text file in the simplest form of a visual point of view with the use of a Windows Form, a button and a multiline text field.
Read a text file in Visual Basic
If you create a new project using Visual Studio 2010 or any other any other issue, make sure you at least have a TextBox1, TextBox2 and Button1 one in your form Form1.

Then copy and paste the following code in Form1.vb:

Public Class Form1
    Private OpenFileDialog As OpenFileDialog

    Public Sub New()

        ' This call is required by the designer.
        OpenFileDialog = New OpenFileDialog
        OpenFileDialog.Filter = "text files|*.txt"
       TextBox2.ScrollBars = ScrollBars.Both
        TextBox1.ReadOnly = True
        Button1.Text = "open..."
        Me.Text = My.Application.Info.AssemblyName

    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If OpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            TextBox1.Text = OpenFileDialog.FileName
            Dim oReader As New System.IO.StreamReader(TextBox1.Text)
                TextBox2.Text = TextBox2.Text & oReader.ReadLine & vbCrLf
            Loop Until oReader.EndOfStream = True
            oReader.Close() 'important to close the open file
        End If
    End Sub

End Class

How the program is relatively simple to explain, but it is always good to remember how it works.
First, the StreamReader object is used to access the text file for reading. StreamReader is not the only technology that exists in the world to access a text file, but it is relatively simple and full Dotnet.
Then, in almost all cases reading algorithm for reading text files, the program must read from file portion at a time and use a loop is inevitable to go through the file. In the example, we use the ReadLine method which means it makes reading the text file line by line. The loop stops when playback reaches the end of the text file.
Finally, the most important thing in any open file, it is essential to close the open file and use the close method allows us to close the text file.
The final content of the text file is imported into the TextBox2.

You can download the example used for this section located at the end of this article.

I'll add a personal note. I have many projects and it is for this reason that I can not devote much time to write articles on blogspot. Be assured that I remain very active in the world of computing and programming with today's technologies.

Download the sample project:

No comments:

Post a Comment