HOW do I count the Number of lines in a text file

D

Daniel Kaseman

I'm using the streamreader stuff. I know how to write and append, but I
don't know how to get VB to return the number of lines that there are in the
sequential access file that I'm working with.

Example:
I've written 40 lines to the file. I know that, but how do I get the
computer to tell me how many lines I have writte to the file? something
like io.file.linecount would be nice, but I'm not finding anything like that
anywhere.

Thanks
 
H

Herfried K. Wagner [MVP]

Daniel Kaseman said:
I'm using the streamreader stuff. I know how to write and append, but I
don't know how to get VB to return the number of lines that there are in
the
sequential access file that I'm working with.

You'll either maintain a counter variable while writing lines to the file or
read the file line-by-line using a 'StreamReader' in order to determine the
number of lines.
 
D

Daniel Kaseman

yes, but what is the syntax?

Herfried K. Wagner said:
You'll either maintain a counter variable while writing lines to the file or
read the file line-by-line using a 'StreamReader' in order to determine the
number of lines.
 
C

Cor Ligthert

I'm using the streamreader stuff.
I know how to write and append, but I
don't know how to get VB to return the number of lines that there are in
the
sequential access file that I'm working with.

You cannot write and append with a streamreader
Example:
I've written 40 lines to the file. I know that, but how do I get the
computer to tell me how many lines I have writte to the file?

Where is the file that you have readed, in memory?
something like io.file.linecount would be nice, but I'm not finding
anything like that
anywhere.
This I don't understand absolute not, what should it do, probably is the
file that you have readed in a kind of collection. You can get the
count/length from it.

Cor
 
C

Chris Dunaway

In addition, if all the records are the same length, then you can get
the number of lines by dividing the file size by the record length.
 
C

Crouchie1998

There are two ways I would do this:

1)

Dim intLines As Integer = TextBox1.Lines.Length
MessageBox.Show(intLines, Me.Text)

2)

TextBox1.Text = ""
With OpenFileDialog1
.InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
.Filter = "Text Files (*.txt)|*.txt"
If .ShowDialog <> DialogResult.OK Then Exit Sub
End With
Dim intLines As Integer = 0
Dim sr As New IO.StreamReader(OpenFileDialog1.FileName)
Do While sr.Peek() >= 0
TextBox1.Text += sr.ReadLine() & ControlChars.CrLf
intLines += 1
Loop
sr.Close()
MessageBox.Show(intLines, Me.Text)

I hope this helps

Crouchie1998
BA (HONS) MCP MCSE
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top