Lines-of-code counting for many C# solutions

Eric picture Eric · May 5, 2010 · Viewed 16.3k times · Source

I am currently researching a solution for counting lines of code in C#.

I pretty much need a combination of the following two tools:
http://richnewman.wordpress.com/2007/07/01/c-and-vbnet-line-count-utility/
http://www.locmetrics.com/index.html

My problem is that I need to recursively scan a folder containing a lot of visual studio solutions. So can't really use the first tool without any major work on its code, as it's only able to scan a single solution at a time.
But I also need to split the results for each solution, preferably even the contained projects. This disqualifies the second tool I found. I also found NDepend which suffers from the same problem.

Do you know of any free tools that do what I need? I am unable to find anything suitable.

Answer

Mitch Wheat picture Mitch Wheat · May 5, 2010

NDepend is a great tool designed for measuring and visualising code metrics and complexity.

Powershell would do it:

(dir -Include *.cs -Recurse | select-string .).Count

Counting Lines of Source Code in PowerShell:

Line count per path:

   gci . *.cs -Recurse | select-string . | Group Path

Min / Max / Averages:

   gci . *.cs -Recurse | select-string . | Group Filename | Measure-Object Count -Min -Max -Average

Comment ratio:

   $items = gci . *.cs -rec; ($items | select-string "//").Count / ($items | select-string .).Count


## Count the number of lines in all C# files in (and below) 
## the current directory. 

function CountLines($directory) 
{ 
    $pattern = "*.cs" 
    $directories = [System.IO.Directory]::GetDirectories($directory) 
    $files = [System.IO.Directory]::GetFiles($directory, $pattern) 

    $lineCount = 0 

    foreach($file in $files) 
    { 
        $lineCount += [System.IO.File]::ReadAllText($file).Split("`n").Count 
    } 

    foreach($subdirectory in $directories) 
    { 
        $lineCount += CountLines $subdirectory 
    } 

    $lineCount 
} 

CountLines (Get-Location) 

Also, Line Counter