How to count the number of lines of code in all files in a directory and its subdirectories

advertisements

How to count the number of lines of code in all files in a directory and its subdirectories. eg. I have a directory which has many subdirectories and each subdirectory has many files and I want to count that how many lines of code is written in these files.

I tried many ways but it gives a different result. Can anyone help me to this using C#?

Directory looks like this:

root
   |---view
   |       |--view1.js
   |       |--view2.js
   |---controller
   |            |--cont1.js
   |            |--cont2.js
   |----model
            |--model.js
            |--model.js

I want to give the root path and it returns the total number of lines of codes of all files.


use this code it helped me a lot

int lineCount = 0;

string[] files = Directory.GetFiles(@"your directory path", "*.extension", SearchOption.AllDirectories);

foreach (string filePath in files)
{
    lineCount += File.ReadAllLines(@filePath).Length;
}
Console.Out.WriteLine("number of files: " + files.Length);
Console.Out.WriteLine("number of lines in all files: " +  lineCount);