Count # of Lines in .TXT

Is there a way to check the total number of lines in a .txt file?
They don’t have a static format.

Thank you!

@rjackson

  1. Use Read Text file Activity to read the data from text file and will give you output as String and say ‘readTxt’

  2. And then try below expression to get line count.

      Int lineCount = readTxt.Split(Environment.NewLine.ToCharArray).Count
    
2 Likes

Assign a variable to System.IO.File.ReadAllLines("test.txt").Length, where test.txt is your file.

2 Likes

I tried this approach but the lines sometimes are not divided by new line. They are just too long so the sentence continues on the next line.

1 Like

In this case, it’s all on one line. Most likely, the program you’re using to view the file makes it appear that the data is on multiple lines when it is only applying a wraparound effect.

What is your end goal in counting the lines?

@rjackson

Then how you will identify no. of lines ?

I just need to keep track of the total number of rows

When notepad is open, you can enable the status bar and it shows at the bottom the number of lines. I tried to get to the last line with keystrokes and read that text but it’s not working.

Why do you need to keep track of the number of rows? I’m asking because I get the feeling that there will be a simpler way to achieve your overall goal, rather than solving for getting the number of lines in Notepad.

I was asked to record in an Excel the total number of records(rows) for a bunch of files within a folder if that makes sense.

Then using System.IO.File.ReadAllLines("test.txt").Length will be sufficient. This counts the number of rows in each text file accurately. If there is question from your requester around this, let them know about the wraparound feature of text readers. Sometimes what is visible in a reader is not indicative of how the file is actually structured.

Hi Anthony,

This solution is giving me more lines than the actual total number in many of the files, any thoughts?

Can you share your workflow and sample texts? If anything is proprietary, be sure to use dummy data instead.

I realize this is an old thread, but it was very helpful to me.

I used Anthony_Humphries response to create a perfect little utility for what I needed.
It is generic enough, and potentially useful enough that I can share.
Main.xaml (7.6 KB)

The attached generic uitlity/project file:

  1. Prompts the user for a target directory
  2. Evaluates each TXT file in the directory with Anthony’s count method
  3. Writes the filename and row count to a csv file in the same directory
  4. Gives a count of files processed to the user at the end of the process.

Thanks Anthony!