.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal

Home >> Code Snippets >> File Operation >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Calculating the no. of lines in a file

Posted By:Abhisek Panda       Posted Date: October 26, 2009    Points: 10    Category: File Operation    URL: http://www.dotnetspark.com  

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


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend