We all know how to count number of lines in a text file. We can use any one of the below methods to do that.
- Incrementing a counter variable while reading or skipping a line using File System Object (FSO).
- Read all the content using FSO-ReadAll method, split it line by line and put into an array.
- Read the content and count no. of lines using RegExp.
But we have one more approach using System.IO.File.ReadAllLines method which is much better and more efficient than the above methods. Let’s see how it is done.
Dim oFile,strFilePath,inLineCount 'Storing File path in strFilePath variable strFilePath="C:test.txt" 'Creating object for .Net IO File class Set oFile=DotNetFactory.CreateInstance("System.IO.File","") 'Counting no. of lines using Length after reading all the lines using ReadAllLines method inLineCount=oFile.ReadAllLines(strFilePath).Length Set oFile=Nothing
If we want to count no. of lines from a text file which is having more number of lines, then we can go for the above method. This method is faster since there is no need to loop line by line using FSO or put all the lines in an array to get the count.