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
Try
'Open the file
objReader = File.OpenText(strFile)
Catch e As System.Exception
'Display the messages
MessageBox.Show(e.ToString)
MessageBox.Show(e.Message)
'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
Do
Try
'Read a line from the file
strLine = objReader.ReadLine
intLineCount = intLineCount + 1
Catch e As EndOfStreamException
'Display the message
MessageBox.Show(e.Message)
'Exit the Do loop
Exit Do
Finally
'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.Close()
objReader = Nothing
End Sub