C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » File Operations »

Calculating the no. of lines in a file


Posted Date: 26 Oct 2009    Resource Type: Code Snippets    Category: File Operations
Author: Abhisek PandaMember Level: Gold    
Rating: 1 out of 5Points: 10



DESCRIPTION



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



Responses

Author: Danasegarane.A    02 Nov 2009Member Level: Diamond   Points : 1
No need for this Long Line of Code.

This will do the Trick


MessageBox.Show(System.IO.File.ReadAllLines(@"D:\T.txt").Count().ToString());





Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
No. of line  .  Calculating the no. of lines in a file in vb  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: One movement with IsolatedStorage class
Previous Resource: Delete ReadOnly File
Return to Discussion Resource Index
Post New Resource
Category: File Operations


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use