Sunday, February 26, 2012

Read a file line by line to the end in VB.NET

This tutorial it's about reading a file line by line until the end in VB.NET. This is usefull, for instance, if you are using this file as a settings file and you inserted one setting per line then you can read them by order.

Visual Studio screenshot:


Code:


Imports System.IO
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim file_dir As String = "file.txt"
        'parse file
        Try
            Dim sr As StreamReader = New StreamReader(file_dir)
            Do Until sr.EndOfStream
                TextBox1.Text += vbNewLine + sr.ReadLine()
            Loop
            sr.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class

In this case you are reading and adding each line to a textbox but you can read this to a string array and keep the information to work with later. It's also important to use try catch because if the file doesn't exist or you don't have permissions to read it will not crash the application.

No comments:

Post a Comment