Tuesday, August 4, 2015

How to read text files VB.net




Read text files VB.net

Today I will teach you how to read text files (.txt) using VB.Net. Let´s go :D

How to create a project in Visual Studio?

Exists many ways to create a new project in VS. For example, when you open your VS program, in the Start Page you will see the option New Project ... 
If you can´t see the Start Page you can also click in File > New Project > Select Visual Basic > Windows Forms Application
Rename your project name if you want and click OK.
It´s easy! 

Start in the Form

For this tutorial we will need to create a Text file in our Windows to test our application. It´s simple.Open your Notepad write some text. Then save it in Desktop and rename it asReadtextfiles_VB.net.
Now in the form, add a TextBox (or richtextbox) to place the text from the file. The textbox should support MultiLine. You can enable it in the Properties of the textbox or using code like I will show in the example. Center it in the form. Also we need a Button.

The code …

Press Control + Alt + 0 to open the code page.
Click in combobox that is in the top, left side. Select FormX(events) and in the Combobox in the top right side select Load. This will generate the Load Event of the Form
Write the next lines of code:

Private Sub Form3_Load(sender As Object, e As EventArgsHandles Me.Load
        Button1.Text = "Open file ..."
        TextBox1.Multiline = True

    End Sub

Now do the same to the button. Select in the left Button1 and in the right side Click or more simple do double-click in the button in the designer.
Write this:

If System.IO.File.Exists(My.Computer.FileSystem.SpecialDirectories.Desktop &"\Readtextfiles_VB.net.txt"Then 'check if file exists
            TextBox1.Text =System.IO.File.ReadAllText(My.Computer.FileSystem.SpecialDirectories.Desktop &"\Readtextfiles_VB.net.txt"'if true the load the text from the file and insert in the textbox
        Else
            MsgBox("File not found"vbCritical + vbOKOnly"Error"'if false show a messagebox
        End If

Using OpenFileDialog

If you want, you can also you the control OpenFileDialog. Paste this code on you Click event of the button.

Dim openfile As New OpenFileDialog
        openfile.CheckFileExists = True
        openfile.InitialDirectory =My.Computer.FileSystem.SpecialDirectories.MyDocuments
        openfile.Multiselect = False
        openfile.Filter = "Text Files (.txt)|*.txt| Configuration Files (.inf)|*.inf"
        openfile.FilterIndex = 1
        openfile.Title = "Select the text file ..."
        openfile.ShowDialog()
        If DialogResult.OK Then
            TextBox1.Clear()
            TextBox1.Text = System.IO.File.ReadAllText(openfile.FileName)
        End If

No comments:

Post a Comment