Reading files line by line in VB

Reading files line by line in VB

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!

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.