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?
-
26I agree that it doesn't help much but if management are asking for it...– FerminAug 7, 2009 at 14:54
-
38LoC is simply a metric and is particulairly interresting in 2 cases: 1) to get an idea how big the code base is i.e. when you join a new team 2) to measure your progress when trying to make your code base more compact– Piotr OwsiakOct 11, 2010 at 17:07
-
218Some 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.– user753899May 14, 2011 at 18:35
-
92In 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.– user959631Jul 27, 2012 at 14:37
-
90The 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).– PositiveGuyJan 10, 2013 at 22:26
26 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? :)
-
25(The only time I've ever been asked to supply line counts was when upper management was figuring out how much time it would take to migrate all our products overseas so they could shut down our domestic site.)– Greg DAug 7, 2009 at 14:33
-
11(Yes, this includes codegen'd files and comments. No, that doesn't bother me. Designers, gen'd code, and comments need to be maintained, too.)– Greg DAug 10, 2009 at 14:20
-
29very nice, completely forgot about powershell. it should become default replacement for cmd Jan 17, 2010 at 14:40
-
5Excellent! Your ending comment really sums it up, it's a trivial task, so why use a non-trivial tool? Though I really think it should be included in all versions of VS. Oct 1, 2010 at 9:22
-
17If you want to exclude the backing files generated for the XAML, you can just add an -exclude switch:
(dir -exclude *.g.cs -include *.cs,*.xaml -recurse | select-string .).Count
Feb 4, 2014 at 15:03
Visual Studio has built-in code metrics, including lines of code:
Analyze → Calculate Code Metrics
-
14
-
52Warning: This does many other things besides simply line count. It also lists "Maintainability Index", "Cyclomatic Complexity", "Depth of Inheritance", and "Class Coupling", all of which are pretty complicated to compute, and you can't run the metrics for just part of it. What this means is that if your code-base is particularly large, you might be sitting for hours waiting for it. If all you want is line-count, there's much faster solutions out there. Sep 24, 2012 at 17:55
-
10
-
56Too bad this doesn't work with native C++ projects (at least it doesn't in VS2013).– CameronSep 18, 2014 at 18:22
-
7According to MSDN, this count is based on the IL and therefore not reflective of the number of lines of source code. @CyberFox– SinjaiAug 28, 2018 at 6:02
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).
-
19This solution incorrectly includes blank lines, comments, documentation, and split statements. For many applications, those should not count as lines of code. Mar 26, 2014 at 22:32
-
2Although it is slightly inaccurate (if you actually use \n in your code, that line will be double counted), it is still the best answer if you need a ROM of lines of code without a 3rd party tool Aug 20, 2015 at 13:32
-
1You can also select a specific file type by selecting an option
Look at these file types:
dropdown just bellow theenable regular expressions box
.– MoshiOct 24, 2015 at 18:35 -
2Works for very small projects... when you have a 100 million lines of code this will take some time.– marshMay 16, 2016 at 18:18
-
20
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
-
1Often counting lines of code is Just Plain Silly, and quantity does not imply quality. However, a huge team putting a 545,000 lb (545,000 lb!!) Dreamliner in the air is an entirely different accomplishment than launching the ultralite I built single handedly in my garage. And if you think about the number of lines of code in Windows, maybe Mr. Bill meant this in a different way than it is usually taken...? May 13, 2010 at 14:31
-
18None of these seem to apply to Visual Studio 2010, and the slickedit link is broken.– MGOwenJun 29, 2011 at 1:42
-
57You find the LOC feature in Visual Studio 2010 Ultimate under "Analysis > Code metrics" I hope I translated it right. I have the German version. There it is "Analyse" > "Codemetriken berechnen"– OneWorldMar 16, 2012 at 19:08
-
2for Visual Studio 2012 the LoC metric could be find at ANALYZE > Calculate Code Metrics for Solution– tetriDec 17, 2013 at 17:08
-
2Also, VS2012 includes this feature in both the Ultimate and Premium editions (and now Professional as well).– SWaltersDec 17, 2013 at 17:09
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. I hope someone else can find this helpful, let me know if you have any questions or need help getting it to work.
-
25Love the downvote without comment. This shouldn't be allowed. What about my solution doesn't work??? I don't even care about the votes, I just wanted to post an update for VS2012-2013 users. Feb 20, 2014 at 13:33
-
Hard to filter out all generated code (AssemblyInfo etc.) so Analyze/Calculate Code Metrics should be preferred.– MKesperJan 22, 2016 at 9:56
-
5Great job, but please mention about the Use Regular Expression checkbox under the Find Options section. It makes it much easier– GogutzApr 16, 2016 at 18:40
-
2
-
A simpler version if no XML, nor HTML... ^(?([^\r\n])\s)*[^\s+?/]+[^\n]*$.– LastBlowJun 7, 2018 at 16:53
Found this tip: LOC with VS Find and replace
Not a plugin though if thats what you are looking for.
-
I love this one, but I think I found a small error in the expression there. For VB.Net I think it should be ^~(:Wh@')~(:Wh@\#).+ and for C# I think ^~(:Wh@//)~(:Wh@\{:Wh@)~(:Wh@\}:Wh@)~(:Wh@\#).+ That way blank comment lines and compiler directives are properly dealt with. It worked better for me with VB.NET anyway, and C# I haven't tested. Aug 3, 2011 at 14:33
-
^~(:Wh@//)~(:Wh@\{:Wh@)~(:Wh@\}:Wh@)~(:Wh@\#)~(:Wh@$).+ ended up working better for C#, I was getting some lines consisting of just whitespace. Aug 5, 2011 at 14:23
-
Does n't it count all commented lines also? Just lines of CODE please!– HydPhaniApr 15, 2013 at 7:44
-
4Here's one that I crated with that works in VS2012 (the one posted is outdated as of 2010) and only counts lines of code. It excludes all comments, using directives, curly braces, xml directives, blank lines, etc.... to give you a true code only count: ^(?!(\s**))(?!(\s*\-\-\>))(?!(\s*\<\!\-\-))(?!(\s*\n))(?!(\s**\/))(?!(\s*\/*))(?!(\s*\/\/\/))(?!(\s*\/\/))(?!(\s*\}))(?!(\s*\{))(?!(\s(using))).*$ Nov 4, 2013 at 17:43
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.
-
2This is great and super easy to use. Much easier than the Find/Replace solutions and more clear what it's actually doing than the VS Code Metrics option. Just
choco install cloc
and thencloc .
in your solution dir. Job done!– RoryJul 29, 2016 at 12:50 -
2I downloaded the Windows EXE from the CLOC website and ran it in my Visual Studio 2017 website project folder. Worked like a charm. I like the --by-file-by-lang option that lists line count per individual file and language, sorted from largest to smallest.– humbadsMar 29, 2018 at 18:25
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
-
2Visual Studio 2010 also have this metrics. Actually nothing new in VS2012 at all. Nov 14, 2012 at 11:03
-
1Yep, but answers here are from time of vs 2008 and a little bit out of date, why use anything or install some extension when it's a built-in feature. And even it's not new feature many people do not know about it.– RegforNov 14, 2012 at 11:42
-
@MikeChaliy May be second introduction sentence has confused you, so I've rewritten it a little bit to avoid such confusion.– RegforNov 14, 2012 at 11:49
-
6This is not lines of code, but Compiled Lines (ie after it is turned into IL). I think Fermin was looking for pre compiled lines. Apr 19, 2013 at 1:48
-
1I just found out that this tool won't work for C++. It can only analyze managed code. May 5, 2021 at 17:02
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@/#).+
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)
-
12Visual Studio Team System 2008 doesn't manage to count unmanaged code. ;) Feb 3, 2010 at 14:29
-
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.
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:
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.
-
2Not applicable for C/C++ project. Only available for C# and Visual Basic that they are not website projects or shared projects Jul 6, 2021 at 16:00
-
1
You could use:
- SCLOCCount http://www.dwheeler.com/sloccount/- Open source
- loc metrics, http://www.locmetrics.com/ - not open source, but easy to use
Other simple tool For VS2008 (open source): http://www.accendo.sk/Download/SourceStat.zip
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}
Use Menu-> Analyse - > Calculate Code Metrics option in Visual Studio 2010 Ultimate.
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."
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
Here is the Trick.. It counts the Js file also.
http://www.spoiledtechie.com/post/2011/11/22/How-To-Count-Lines-of-Code-in-Visual-Studio.aspx
You can use free tool SourceMonitor
Gives a lot of measures: Lines of Code, Statement Count, Complexity, Block Depth
Has graphical outputs via charts
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
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
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:
In Visual Studio 2015 go to the Analyze Menu and select "Calculate Code Metrics".