Files and Folders

Reading files line by line

It is often useful to read a file line by line, especially if you need to parse the file if you have created your own special file format. Please note that this method is slower than reading the file all at once, so only use it if you really need to load the file line by line!

Dim nFileNum As Integer, sText As String, sNextLine As String, lLineCount As Long

' Get a free file number
nFileNum = FreeFile

' Open Test.txt for input. App.Path returns the path your app is saved in
Open App.Path & "Test.txt" For Input As nFileNum
lLineCount = 1
' Read the contents of the file
Do While Not EOF(nFileNum)
    Line Input #nFileNum, sNextLine
    'do something with it
    'add line numbers to it, in this case!
    sNextLine = lLineCount & " " & sNextLine & vbCrLf
    sText = sText & sNextLine
    lLineCount = lLineCount + 1
Loop
TextBox1.Text = sText

' Close the file
Close nFileNum

Note that the Line Input function returns the current line to sNextLine. This does not include the new line character, so if you are displaying the text you need to add one!

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” - Tom Cargill