Calculating no. of lines in a file.

Posted by Abhisek under VB.NET category on | Views : 2555
The following code demonstrated how to read a file and calculate the no. of lines in it using VB.NET. We are using StreamReader class to process the file and creating its object. After processing the file the no. of lines read will be displayed in a label.

As it is a part of window application first you have to open the file using the OpenFileDialog control and display it in the rich text box.

Private Sub ProcessFile(ByVal strFile As String)
'Declare an object for the StreamReader class
Dim objReader As StreamReader

'Open the file
objReader = File.OpenText(strFile)
Catch e As System.Exception
'Display the messages
'Exit the procedure

Exit Sub
End Try

'Declare variables
Dim intLineCount As Integer = 0
Dim strLine As String, strData As String

'Loop through the file counting the lines and loading the

'Read a line from the file
strLine = objReader.ReadLine
intLineCount = intLineCount + 1

Catch e As EndOfStreamException
'Display the message
'Exit the Do loop

Exit Do


'Concatenate the data to the strData variable
strData = strData & strLine & vbCrLf

End Try

Loop While strLine <> Nothing

'Load the text box

txtData.Text = strData

'Display the number of lines read
lblLinesOfText.Text = "Number of lines read: " & intLineCount - 1

'Clean up
objReader = Nothing

End Sub

Comments or Responses

Login to post response