Is it possible to find the number of lines of code in an entire solution? I've heard of MZ-Tools, but is there an open source equivalent?
-
29I agree that it doesn't help much but if management are asking for it...Fermin– Fermin2009-08-07 14:54:48 +00:00Commented Aug 7, 2009 at 14:54
-
227Some people here are saying that counting lines of code is useless without giving it good thought. It is quite useful as it is a metric that should generally be minimized. It is a simple way to measure complexity of the solution(not efficiency) and if the problem is known to be simple, the more lines of code, generally the lower the quality. Another thing is why do people bother responding if it is just to say the question is a bad one? What would you think if a teacher told you your question just shouldn't be asked.user753899– user7538992011-05-14 18:35:21 +00:00Commented May 14, 2011 at 18:35
-
4LoC is useful as long as you don't make too much of it. It's a decent indicator of the overall size and level of complexity of the application, but remember that it's easy to game line counts - anyone can find ways to pack lots of statements onto one line, or break a simple statement into lots of lines. Taking a look at it when you take over a new project is generally useful, but setting goals and measuring progress based on it is generally a bad idea.Mason– Mason2012-04-13 19:36:07 +00:00Commented Apr 13, 2012 at 19:36
-
98In VS2010 there is a in-built tool that counts all lines of code and other values too: Go to View -> Other Windows -> Code metrics results. A little button in the corner that looks like a calendar, click that, the tooltip should say Calculate code metrics for soulution, and let VS do it's thing.user959631– user9596312012-07-27 14:37:39 +00:00Commented Jul 27, 2012 at 14:37
-
96The person doesn't always need to tell you why they want to count code. When the question is this simply stated, the case around why is irrelevant. Just answer his question. I hate that. There are times to ask why when clearly you need to and then there are times you don't (when you personally don't see a need...and are just badgering the poster in arrogance).PositiveGuy– PositiveGuy2013-01-10 22:26:07 +00:00Commented Jan 10, 2013 at 22:26
27 Answers
I've found PowerShell useful for this. I consider LoC to be a pretty bogus metric anyway, so I don't believe anything more formal should be required.
From a smallish solution's directory:
PS C:\Path> (gci -include *.cs,*.xaml -recurse | select-string .).Count
8396
PS C:\Path>
That will count the non-blank lines in all the solution's .cs and .xaml files. For a larger project, I just used a different extension list:
PS C:\Other> (gci -include *.cs,*.cpp,*.h,*.idl,*.asmx -recurse | select-string .).Count
909402
PS C:\Other>
Why use an entire app when a single command-line will do it?
15 Comments
(dir -exclude *.g.cs -include *.cs,*.xaml -recurse | select-string .).CountVisual Studio has built-in code metrics, including lines of code:
Analyze → Calculate Code Metrics
29 Comments
I used Ctrl+Shift+F. Next, put a \n in the search box and enable regular expressions box. Then in the find results, in the end of the screen are the number of files searched and lines of code found.
You can use [^\n\s]\r\n to skip blank and space-only lines (credits to Zach in the comments).
12 Comments
Look at these file types: dropdown just bellow the enable regular expressions box .[^\n\s]\r\n skips blank lines, even with spaces in them.An open source line counter for VS2005, 2003 and 2002 is available here:
There is also discussion of creating a line counting VS addin, complete with code on Codeproject, here
http://www.codeproject.com/KB/macros/LineCounterAddin.aspx
Also Slick Edit Gadgets have a nice line-counter, here:
http://www.slickedit.com/products/slickedit
and Microsoft Visual Studio Team System 2008 includes a good line counter.
Just remember though:
Measuring programming progress by lines of code is like measuring aircraft building progress by weight. Bill Gates
12 Comments
Here's an update for Visual Studio 2012/2013/2015 for those who want to do the "Find" option (which I find to be the easiest): This RegEx will find all non-blank lines with several exclusions to give the most accurate results.
Enter the following RegEx into the "Find" box. Please make sure to select the "Use Regular Expressions" option. Change the search option to either "Current Project" or "Entire Solution" depending on your needs. Now select "Find All". At the bottom of the Find Results window, you will see "Matching Lines" which is the lines of code count.
^(?!(\s*\*))(?!(\s*\-\-\>))(?!(\s*\<\!\-\-))(?!(\s*\n))(?!(\s*\*\/))(?!(\s*\/\*))(?!(\s*\/\/\/))(?!(\s*\/\/))(?!(\s*\}))(?!(\s*\{))(?!(\s(using))).*$
This RegEx excludes the following items:
Comments
// This is a comment
Multi-Line comments (assuming the lines are correctly commented with a * in front of each line)
/* I am a
* multi-line
* comment */
XML for Intellisense
/// <summary>
/// I'm a class description for Intellisense
/// </summary>
HTML Comments:
<!-- I am a HTML Comment -->
Using statements:
using System;
using System.Web;
Opening curly braces:
{
Closing curly braces:
}
Note: anything between the braces would be included in the search, but in this example only 4 lines of code would count, instead of 18 actual non-blank lines:
public class Test
{
/// <summary>
/// Do Stuff
/// </summary>
public Test()
{
TestMe();
}
public void TestMe()
{
//Do Stuff Here
/* And
* Do
* Stuff
* Here */
}
}
I created this to give me a much more accurate LOC count than some previous options, and figured I would share. The bosses love LOC counts, so I'm stuck with it for a while.
7 Comments
Found this tip: LOC with VS Find and replace
Not a plugin though if thats what you are looking for.
4 Comments
cloc is an excellent commandline, Perl-based, Windows-executable which will break down the blank lines, commented lines, and source lines of code, grouped by file-formats.
Now it won't specifically run on a VS solution file, but it can recurse through directories, and you can set up filename filters as you see fit.
Here's the sample output from their web page:
prompt> cloc perl-5.10.0.tar.gz
4076 text files.
3883 unique files.
1521 files ignored.
http://cloc.sourceforge.net v 1.07 T=10.0 s (251.0 files/s, 84566.5 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code scale 3rd gen. equiv
-------------------------------------------------------------------------------
Perl 2052 110356 112521 309778 x 4.00 = 1239112.00
C 135 18718 22862 140483 x 0.77 = 108171.91
C/C++ Header 147 7650 12093 44042 x 1.00 = 44042.00
Bourne Shell 116 3402 5789 36882 x 3.81 = 140520.42
Lisp 1 684 2242 7515 x 1.25 = 9393.75
make 7 498 473 2044 x 2.50 = 5110.00
C++ 10 312 277 2000 x 1.51 = 3020.00
XML 26 231 0 1972 x 1.90 = 3746.80
yacc 2 128 97 1549 x 1.51 = 2338.99
YAML 2 2 0 489 x 0.90 = 440.10
DOS Batch 11 85 50 322 x 0.63 = 202.86
HTML 1 19 2 98 x 1.90 = 186.20
-------------------------------------------------------------------------------
SUM: 2510 142085 156406 547174 x 2.84 = 1556285.03
-------------------------------------------------------------------------------
The third generation equivalent scale is a rough estimate of how much code it would take in a third generation language. Not terribly useful, but interesting anyway.
2 Comments
choco install cloc and then cloc . in your solution dir. Job done!Answers here are a little bit out of date, may be from vs 2008 time. Because in newer Visual Studio versions 2010/2012, this feature is already built-in. Thus there are no reason to use any extension or tools for it.
Feature to count lines of code - Calculate Metrics. With it you can calculate your metrics (LOC, Maintaince index, Cyclomatic index, Depth of inheritence) for each project or solution.
Just right click on solution or project in Solution Explorer,

and select "Calculate metrics"

Later data for analysis and aggregation could be imported to Excel. Also in Excel you can filter out generated classes, or other noise from your metrics. These metrics including Lines of code LOC could be gathered also during build process, and included in build report
9 Comments
Regular expressions have changed between VS2010 and 2012, so most of the regular expression solutions here no longer work
(^(?!(\s*//.+)))+(^(?!(#.+)))+(^(?!(\s*\{.+)))+(^(?!(\s*\}.+)))+(^(?!(\s*\r?$)))+
Will find all lines that are not blank, are not just a single bracket ( '{' or '}' ) and not just a #include or other preprocessor.
Use Ctrl-shift-f and make sure regular expressions are enabled.
The corresponding regular expression for VS 2010 and older is
^~(:Wh@//.+)~(:Wh@\{:Wh@)~(:Wh@\}:Wh@)~(:Wh@/#).+
Comments
In Visual Studio Team System 2008 you can do from the menu Analyze--> 'Calculate Code Metrics for Solution' and it will give you a line count of your entire solution (among other things g)
For future readers I'd like to advise the DPack extension for Visual Studio 2010.
It's got a load of utilities built in including a line counter which says how many lines are blank, code, and etc.
1 Comment
A simple solution is to search in all files. Type in "*" while using wildcards. Which would match all lines. At the end of the find results window you should see a line of the sort:
Matching lines: 563 Matching files: 17 Total files searched: 17
Of course this is not very good for large projects, since all lines are mached and loaded into memory to be dispayed at the find results window.
Reference:
Comments
In Visual Studio 2019, from the top menu you need to select:
'Analyze' -> 'Calculate Code Metrics' -> 'For Solution'
This works in both Visual Studio 2019 Professional and Enterprise.
2 Comments
You could use:
- SCLOCCount http://www.dwheeler.com/sloccount/- Open source
- loc metrics, http://www.locmetrics.com/ - not open source, but easy to use
Comments
Other simple tool For VS2008 (open source): http://www.accendo.sk/Download/SourceStat.zip
Comments
Obviously tools are easier, but I feel cool doing this in powershell:)
This script finds all the .csproj references in the .sln file, and then within each csproj file it locates files included for compilation. For each file that is included for compilation it creates an object with properties: Solution, Project, File, Lines. It stores all these objects in a list, and then groups and projects the data as needed.
#path to the solution file e.g. "D:\Code\Test.sln"
$slnFile = "D:\Code\Test.sln"
#results
$results = @()
#iterate through .csproj references in solution file
foreach($projLines in get-item $slnFile | Get-Content | Select-String '".*csproj')
{
$projFile = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($slnFile), [regex]::Match($projLines,'[^"]*csproj').Value)
$projFolder = [System.IO.Path]::GetDirectoryName($projFile)
#from csproj file: get lines for files to compile <Compile Include="..."/>
$includeLines = get-item $projFile | Get-Content | Select-String '<Compile Include'
#count of all files lines in project
$linesInProject = 0;
foreach($fileLine in $includeLines)
{
$includedFilePath = [System.IO.Path]::Combine($projFolder, [Regex]::Match($fileLine, '"(?<file>.*)"').Groups["file"].Value)
$lineCountInFile = (Get-Content $includedFilePath).Count
$results+=New-Object PSObject -Property @{ Solution=$slnFile ;Project=$projFile; File=$includedFilePath; Lines=$lineCountInFile }
}
}
#filter out any files we dont need
$results = $results | ?{!($_.File -match "Designer")}
#print out:
"---------------lines per solution--------------"
$results | group Solution | %{$_.Name + ": " + ($_.Group | Measure-Object Lines -Sum).Sum}
"---------------lines per peoject--------------"
$results | group Project | %{$_.Name + ": " + ($_.Group | Measure-Object Lines -Sum).Sum}
Comments
You can use the Visual Studio Code Metrics PowerTool 10.0. It's a command-line utility that calculates a few metrics on managed code for you (including lines of code). You can get a VS 2010 plugin that brings the tool into Visual Studio, and makes it as quick as selecting the menu item and clicking "Analyze Solution."
Comments
Agree with Ali Parr. The WndTab Line Counter addin is a such tool. http://www.codeproject.com/KB/macros/linecount.aspx
It's also a good idea to search from download site to find some related tool. http://www.cnet.com/1770-5_1-0.html?query=code+counter&tag=srch
Comments
You can use free tool SourceMonitor
Gives a lot of measures: Lines of Code, Statement Count, Complexity, Block Depth
Has graphical outputs via charts
Comments
Try neptuner. It also gives you stuff like spaces, tabs, Lines of comments in addition to LoC. http://neptuner.googlecode.com/files/neptuner_0_30_windows.zip
Comments
You can use the Project Line Counter add-in in Visual Studio 2010. Normally it doesn't work with Visual Studio 2010, but it does with a helpful .reg file from here: http://www.onemanmmo.com/index.php?cmd=newsitem&comment=news.1.41.0
Comments
I came up with a quick and dirty powershell script for counting lines in a folder structure. It's not nearly as full featured as some of the other tools referenced in other answers, but I think it's good enough to provide a rough comparison of the size of code files relative to one another in a project or solution.
The script can be found here:
Comments
In Visual Studio 2015 go to the Analyze Menu and select "Calculate Code Metrics".
2 Comments
Here's a script you can run in C# Interactive to produce a simple report of the number of lines in each folder, and also each subfolder that contains files with a certain minimum number of lines. The report-gathering method accepts
- A
basePath(root folder for analysis) - A
folderFilter(path,folder)for deciding whether to include a folder and its subfolders in the report - A
filePatternsuch as"*.cs"or just"*"for all files - A
fileFilter(path,file)function for deciding whether to count lines in a particular file - A
lineFilter(text)function for deciding whether to include a particular line in the count.
using System.IO;
using System.Collections.Generic;
// Recursively scans directories, counting lines in each one...
class LinesReport
{
public string BasePath; // Parent path
public string FolderName; // Folder name
public int LocalLines; // Lines in this folder
public int TotalLines; // Lines in this folder and subfolders
public List<LinesReport> Subfolders = new();
public string Error;
}
static List<LinesReport> GetLinesReports(string basePath, Func<string, string, bool>? folderFilter, string filePattern, Func<string, string, bool>? fileFilter, Predicate<string>? lineFilter)
{
List<LinesReport> results = new();
foreach (var dir in Directory.GetDirectories(basePath)) {
var report = new LinesReport() { BasePath = basePath, FolderName = Path.GetFileName(dir) };
if (folderFilter == null || folderFilter(basePath, report.FolderName)) {
try {
// Count lines in files in current folder
foreach (var path in Directory.GetFiles(dir, filePattern)) {
var fileName = Path.GetFileName(path);
if (fileFilter == null || fileFilter(dir, fileName)) {
try {
report.LocalLines += CountLines(path, lineFilter);
}
catch (IOException e) {
report.Error = e.Message;
}
}
}
// Get reports for subfolders
report.Subfolders = GetLinesReports(dir, folderFilter, filePattern, fileFilter, lineFilter);
// Sum up total up lines
report.TotalLines = report.LocalLines + report.Subfolders.Sum(r => r.TotalLines);
results.Add(report);
}
catch (IOException e) {
report.Error = e.Message;
}
}
}
return results;
}
static int CountLines(string path, Predicate<string>? lineFilter)
{
int count = 0;
foreach (string line in File.ReadAllLines(path))
if (lineFilter == null || lineFilter(line))
count++;
return count;
}
static void PrintLinesReports(List<LinesReport> reports, int minLines, int indent = 0)
{
foreach (var report in reports) {
if (report.TotalLines >= minLines || indent == 0 || report.Error != null) {
Console.WriteLine("{0}{1}: {2} {3}", new string(' ', indent), report.FolderName, report.TotalLines, report.Error);
PrintLinesReports(report.Subfolders, minLines, indent + 2);
}
}
if (indent == 0)
Console.WriteLine($"Total: {reports.Count} folders in {reports[0].BasePath} with {reports.Sum(r => r.TotalLines)} lines");
}
var results = GetLinesReports(@"C:\Dev\MyProject",
(p, dir) => !dir.StartsWith(".") && !dir.EndsWith("Test") && dir is not ("bin" or "obj" or "node_modules" or "tests"),
"*.cs", (p, name) => !name.EndsWith(".Designer.cs"),
line => line.Length != 0);
PrintLinesReports(results, 100);
Call PrintLinesReports(results, minLines) where minLines is the minimum number of matching lines of text required to include a folder in the output. This prints a report of all the folders and subfolders, like:
Documentation: 0
MyProject: 5757
RazorPages: 2335
Controllers: 3241
Contracts: 237
Helpers: 1378
Middleware: 181
Total: 2 folders in C:\Dev\MyProject with 5757 lines
Comments
Here's a vb.net console application that counts lines of code within a folder structure. It has some tweaks for our specific needs, like some file extensions which only we use, and we have two folder structures involved in one project. I'm sure this will fulfil most peoples needs though, and it should be easy to migrate to c# with a code converter.
The built in tools > calculate code metrics for solution might suit some people but it doesn't count C/C++ and it doesn't give totals. The solution below gives a grand total, a total per top level folder, a total per file extension and a "total per file extension per top level folder". You can tweak the case statement to include other file extensions, and you can tweak the "if" statements for files you want to exclude.
Imports System.IO
Imports System.Text
Module Module1
Private extensionsglobal As New Dictionary(Of String, Integer)
Private output As New List(Of String)
Private outputextensions As New List(Of String)
Sub Main()
Dim root As String = "c:\rootfolder"
Dim dir As String = root & "\code"
Dim numberoflines As Integer = DirectoryWalk(dir, 1, Nothing)
Dim dir2 As String = root & "\someotherfolder\subfolder\sub1"
numberoflines += DirectoryWalk(dir2, 1, Nothing)
output.Add("Total lines of code: " & numberoflines.ToString.PadLeft(10))
For Each key As String In extensionsglobal.Keys
output.Add("Lines of code in files with extension " & key.PadRight(10) & " : " & extensionsglobal(key).ToString.PadLeft(10))
Next
Console.WriteLine(String.Join(vbCrLf, output.ToArray))
Console.WriteLine(String.Join(vbCrLf, outputextensions.ToArray))
Console.WriteLine("Finished")
Console.ReadLine()
End Sub
Private Function DirectoryWalk(ByVal dir As String, level As Integer, extensions As Dictionary(Of String, Integer)) As Integer
If level <= 2 Then
Console.WriteLine("Processing: " & dir)
End If
Dim numberoflines As Integer = 0
Dim d As New DirectoryInfo(dir)
Dim extensionsthis As Dictionary(Of String, Integer)
If level <= 2 Then
extensionsthis = New Dictionary(Of String, Integer)
Else
extensionsthis = extensions
End If
For Each fil As FileInfo In d.GetFiles()
Select Case fil.Extension
Case ".vb", ".cs", ".js", ".html", ".htm", ".css", ".sql", ".php", ".asp", ".aspx", ".asmx",
".c", ".cpp", ".h", ".sh", ".bat", ".cmd", ".ps1",
".htaccess", ".htpasswd", ".htgroups", ".htacl", ".amsx"
If fil.Name Like "upgradelog*" Then Continue For
If fil.Name Like "*.min.css" Then Continue For
If fil.Name Like "*.min.js" Then Continue For
If fil.Name Like "*temp.js" Then Continue For
If fil.Name Like "select2*.js" Then Continue For
If fil.Name Like "selectize*.js" Then Continue For
If fil.Name Like "quagga*.js" Then Continue For
If fil.Name = "d3.js" Then Continue For
If fil.Name = "jq3.js" Then Continue For
Dim lines() As String = IO.File.ReadAllLines(fil.FullName)
numberoflines += lines.Count
If extensionsglobal.ContainsKey(fil.Extension) Then
extensionsglobal(fil.Extension) += lines.Count
Else
extensionsglobal.Add(fil.Extension, lines.Count)
End If
If extensionsthis.ContainsKey(fil.Extension) Then
extensionsthis(fil.Extension) += lines.Count
Else
extensionsthis.Add(fil.Extension, lines.Count)
End If
End Select
Next
Dim d2 As DirectoryInfo() = d.GetDirectories()
For Each d3 As DirectoryInfo In d2
numberoflines += DirectoryWalk(d3.FullName, level + 1, extensionsthis)
Next
If level <= 2 Then
output.Add("Lines of code in folder : " & numberoflines.ToString.PadLeft(10) & " in folder : " & dir)
If level = 2 Then
outputextensions.Add("Lines of code in folder : " & numberoflines.ToString.PadLeft(10) & " in folder : " & dir)
For Each key As String In extensionsthis.Keys
outputextensions.Add(" code in files with extension " & key.PadRight(10) & " : " & extensionsthis(key).ToString.PadLeft(10))
Next
End If
End If
Return numberoflines
End Function
End Module