How do you count the lines of code in a Visual Studio solution?
Asked Answered
O

28

941

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?

Oaks answered 7/8, 2009 at 13:35 Comment(16)
I agree that it doesn't help much but if management are asking for it...Oaks
It's not neccesarily programming related, but it might give you an indication of the complexity of your code base. I was quite surprised to learn the size of our solution, using the PS script from Greg D.Catamenia
Some 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.Slumberous
LoC 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.Grindstone
If you've spent months writing a WPF app, and your boss "just" wants you to change it to WinForms because somebody has been in his ear and said WPF was bad, you might want to "just" give him the faintest idea what he's asking.Barfuss
In 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.Balbriggan
Sometimes a begineer programmer need some numbers to make himself feel like he accomplish something.Abducent
@KirillV.Lyadvinsky very useful as a component of estimating the cost to port a library from one language to anotherPraxiteles
The 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).Cassiterite
The VS2010 (and even VS2012) built-in solution only seems to count LOC on the managed projects. If you are looking to count C++ lines you're outta luck.Jugurtha
Go to View -> Other Windows -> Code Metrics Results You can export the result to Excel and filter by project / namespace etc.Jaguarundi
As a programmer that has code reviewed for PCI requirements, this is an absolute necessity to know line counts. The cost goes up the mores lines of code you have. =)Vasos
I believe code metrics in VS does not count lines of xml style source code files like XAML.Distributive
@Oaks I suggest you update the checkmarked answer. Herter's answer below (245 votes) is correct, as Visual Studio now includes this feature.Dovap
Is there a way to count the lines of code on a day or something like this?Sphenogram
It's not quantity, but quality that counts ;)Pyrone
H
749

Visual Studio has built-in code metrics, including lines of code:

Analyze → Calculate Code Metrics

Heath answered 1/3, 2011 at 2:25 Comment(29)
Ultimate and Premium, I thinkDarden
Premium does include it. However, it seems to skip over code files where the type is defined in xaml.Wordsworth
Warning: 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.Isagoge
@Darrel Hoffman - that is of course very true.. You should use a more lightweight option if you want the LOC on a huge projectHeath
Lines of code that this calculates (in VS2010) are approximation of the lines of executable code.Ergo
also on vs2012 ultimate =)Monomer
@Darrel Hoffman it's not calculating number of lines, but pure code lines (empty lines, parentheses, comments, and usings are not calculated here)Ecclesiology
@HamzehSoboh Sure, but it'll still take forever calculating all that other stuff if your codebase is of any significant size. I was working on a project with LOC in billions (not exaggerating) when I posted that. This tool was essentially useless for that, unless you wanted to just let it run overnight...Isagoge
Too bad this doesn't work with native C++ projects (at least it doesn't in VS2013).Suk
I need to count lines for several projects that still do not compile, and this requires the code is currently compiling, so this is not a valid option in use cases like mine.Berriman
Yeah I agree it isnt perfect, but in most cases it will sufficeHeath
Down-voted because after 20 minutes i can only see Loc per project and not for the entire solution. The results cant even be copy pasted to Excel.Armageddon
@Armageddon there's a dedicated button to export the data to Excel, right above the results.Roundtheclock
It should be mentioned that this solution will exclude any code that's marked with GeneratedCodeAttribute. Meaning any code that's generated by a designer, a tool, etc.Roundtheclock
@VSG24, where exactly, could you please elaborate?Woosley
@sunnymoon Same place. Top menu -> Analyze -> Run Code Analysis -> On Solution. You can access the same functionality from View -> Other Windows -> Code Metrics ResultsSlipperwort
It's worth noting that according to msdn the amount of LoC calculated is based on IL, not the actual code.Levins
This might be useful for pure .NET code, but for example, in a web application where you have JavaScript, HTML, CSS, and possibly other code beyond .NET, this is unhelpful. I ran this against my Angular application that is 100% JavaScript/HTML/CSS and was informed it contains 0 lines of code.Oligarchy
Works fine with Visual Studio 2017 EnterpriseErund
revisiting this thread i used this tool but it doesn't work like you'd expect i counted the lines by myself i got about 1100 but this tool just showed about 600 lines. I'm guessing they only measure function code and not structural code. All my delegates totalled 0 lines of code.Cassady
According to MSDN, this count is based on the IL and therefore not reflective of the number of lines of source code. @CassadySmuts
That is not exact as it doesn't count your lines of code. Instead, you'll get the count of the IL compiled lines.Trona
Lines of Code - Indicates the approximate number of lines in the code. The count is based on the IL code and is therefore not the exact number of lines in the source code file. A very high count might indicate that a type or method is trying to do too much work and should be split up. It might also indicate that the type or method might be hard to maintain.Fleur
Does this count empty lines?Horsehide
@FernandoG yes. they fixed the documentation concerning this recently. learn.microsoft.com/de-de/visualstudio/code-quality/…Lilienthal
Still works in VS2019...BUT..."only for VB and C# projects that are not web or shared projects" (you get a warning if there are any such). If you are in any other project type then the option - in the main menu Analyze or in the context ment - is not even available!Parboil
This method is deprecated, not supported in 2019Door
This worked in VS2019 for ASP.NET 5 project BUT it completely ignored all the razor .cshtml files, .js, .css and other "non C#" stuff. Use the powershell answerChore
available on VS 2022 community editionChurchill
J
984

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? :)

Jovitajovitah answered 7/8, 2009 at 14:2 Comment(14)
(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.)Jovitajovitah
(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.)Jovitajovitah
very nice, completely forgot about powershell. it should become default replacement for cmdPeril
Excellent! 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.Catamenia
If 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 .).CountVest
Beautiful. Keep in mind -exclude can be used to ignore files by name as well as extension; the command as given here on a relatively modest-sized application returned 1.8 million LoC, then I ignored a particular auto-generated file for a service proxy, as well as designer files for the UI, and got the much more realistic 118k lines of actual human-written code.Carlottacarlovingian
Perfect, I prefer this to installing yet another plugin for VS or using an entire external program!Rossi
Thats nice. Can I somehow exclude lines with fewer than a certain amount of characters, like { and } lines and such? Also I would like to exclude lines starting with "using" I think that could get closer to the amount of lines that where actually written by the programmer.Disrespectful
@Ravior- You're missing the point. Lines of code is a terrible metric for anything meaningful the moment you start caring about minutiae like that. Tweaking the detailed rules around how it's calculated is effectively meaningless because it's fundamentally a relative (and mostly useless) measure.Jovitajovitah
Nice!! since I am working on a big project, I wrote lots of small stand along programs, it's better to count what's in a folder instead of a solutionSelffertilization
what is the purpose of the period in "select-string ."?Tetraspore
It's a regex pattern, the . is a wildcard character. See select-string docs (learn.microsoft.com/en-us/powershell/module/…) and powershell regex docs (learn.microsoft.com/en-us/powershell/module/…)Jovitajovitah
this should be more efficient: dir -Recurse -Include *.ts,*.tsx -Exclude *node_modules* | Get-Content | Measure-Object -Line How to count all the lines of code in a directory recursively on Windows?Balkan
For the WSL users try grep -Pr --include=*.{cs,xaml} '[\S]' * | wc -lAbecedarian
H
749

Visual Studio has built-in code metrics, including lines of code:

Analyze → Calculate Code Metrics

Heath answered 1/3, 2011 at 2:25 Comment(29)
Ultimate and Premium, I thinkDarden
Premium does include it. However, it seems to skip over code files where the type is defined in xaml.Wordsworth
Warning: 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.Isagoge
@Darrel Hoffman - that is of course very true.. You should use a more lightweight option if you want the LOC on a huge projectHeath
Lines of code that this calculates (in VS2010) are approximation of the lines of executable code.Ergo
also on vs2012 ultimate =)Monomer
@Darrel Hoffman it's not calculating number of lines, but pure code lines (empty lines, parentheses, comments, and usings are not calculated here)Ecclesiology
@HamzehSoboh Sure, but it'll still take forever calculating all that other stuff if your codebase is of any significant size. I was working on a project with LOC in billions (not exaggerating) when I posted that. This tool was essentially useless for that, unless you wanted to just let it run overnight...Isagoge
Too bad this doesn't work with native C++ projects (at least it doesn't in VS2013).Suk
I need to count lines for several projects that still do not compile, and this requires the code is currently compiling, so this is not a valid option in use cases like mine.Berriman
Yeah I agree it isnt perfect, but in most cases it will sufficeHeath
Down-voted because after 20 minutes i can only see Loc per project and not for the entire solution. The results cant even be copy pasted to Excel.Armageddon
@Armageddon there's a dedicated button to export the data to Excel, right above the results.Roundtheclock
It should be mentioned that this solution will exclude any code that's marked with GeneratedCodeAttribute. Meaning any code that's generated by a designer, a tool, etc.Roundtheclock
@VSG24, where exactly, could you please elaborate?Woosley
@sunnymoon Same place. Top menu -> Analyze -> Run Code Analysis -> On Solution. You can access the same functionality from View -> Other Windows -> Code Metrics ResultsSlipperwort
It's worth noting that according to msdn the amount of LoC calculated is based on IL, not the actual code.Levins
This might be useful for pure .NET code, but for example, in a web application where you have JavaScript, HTML, CSS, and possibly other code beyond .NET, this is unhelpful. I ran this against my Angular application that is 100% JavaScript/HTML/CSS and was informed it contains 0 lines of code.Oligarchy
Works fine with Visual Studio 2017 EnterpriseErund
revisiting this thread i used this tool but it doesn't work like you'd expect i counted the lines by myself i got about 1100 but this tool just showed about 600 lines. I'm guessing they only measure function code and not structural code. All my delegates totalled 0 lines of code.Cassady
According to MSDN, this count is based on the IL and therefore not reflective of the number of lines of source code. @CassadySmuts
That is not exact as it doesn't count your lines of code. Instead, you'll get the count of the IL compiled lines.Trona
Lines of Code - Indicates the approximate number of lines in the code. The count is based on the IL code and is therefore not the exact number of lines in the source code file. A very high count might indicate that a type or method is trying to do too much work and should be split up. It might also indicate that the type or method might be hard to maintain.Fleur
Does this count empty lines?Horsehide
@FernandoG yes. they fixed the documentation concerning this recently. learn.microsoft.com/de-de/visualstudio/code-quality/…Lilienthal
Still works in VS2019...BUT..."only for VB and C# projects that are not web or shared projects" (you get a warning if there are any such). If you are in any other project type then the option - in the main menu Analyze or in the context ment - is not even available!Parboil
This method is deprecated, not supported in 2019Door
This worked in VS2019 for ASP.NET 5 project BUT it completely ignored all the razor .cshtml files, .js, .css and other "non C#" stuff. Use the powershell answerChore
available on VS 2022 community editionChurchill
M
393

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).

Morelos answered 21/2, 2012 at 20:46 Comment(12)
This solution incorrectly includes blank lines, comments, documentation, and split statements. For many applications, those should not count as lines of code.Drinker
Although 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 toolTerceira
You can also select a specific file type by selecting an option Look at these file types: dropdown just bellow the enable regular expressions box .Marietta
You can disable regular expressions to know actual usage of "\n"Herein
Works for very small projects... when you have a 100 million lines of code this will take some time.Cutpurse
Works great! I wanted to know how many lines of code I've programmed in the last week. 15,000 lines. That's prettty cool :DPhysiological
Perfect solution. To be more accurate, "Look for these files" *.cs; *.aspx,*.sql, *.css, *.skin, *.master,*.xsd,*.txt,*.ascx,*.config,*.sitemap. This will give accurate line counts in ASP.NET Web Application.Cerotype
I like this answer because it can include JS, HTML, CSS, etc, which ended up making a huge difference (like 25 times higher)Inesita
[^\n\s]\r\n skips blank lines, even with spaces in them.Arkose
I used the two methods. The line count with [^\n\s]\r\n to skip blank lines gives me 45,000 lines and the menu > Analyze > Calculate Code Metrics > For Solution method shows me 15,000 lines of source code. So.. this for me is about a 3:1 ratio. So use the line count, divide by 3 and you get a good estimate.Bathysphere
@ZachMierzejewski 's solution does not count lines of code that end with a space character before new lineInfinite
For my solution it counted almost 500,000 lines in a couple of seconds, very nice.Built
P
222

An open source line counter for VS2005, 2003 and 2002 is available here:

http://www.wndtabs.com/

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

Poultryman answered 7/8, 2009 at 13:43 Comment(12)
Often 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...?Styracaceous
None of these seem to apply to Visual Studio 2010, and the slickedit link is broken.Jolyn
You 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"Unhook
Lines of code can be somewhat useful if you want to do a comparison of #Bugs/LOC. Not that this metric should be used to hire/fire people but as a personal goal to reduce that number, actually reduce both LOC to achieve same output and bugs/LOCParedes
@Unhook Only in Premium and above. Professional doesn't have it.Truly
@Truly You are right. So, we can say, you need either Premium or Ultimate. Also see the wikipedia article under the headlines "Editions feature grid" and "Visual Studio Ultimate 2010"Unhook
I agree with the quote of BG but LOC are a great indicator of how much is going to cost to maintain a software project, maybe that quote is a reason of how MS understimate this indicator.Morelos
for Visual Studio 2012 the LoC metric could be find at ANALYZE > Calculate Code Metrics for SolutionBrio
Also, VS2012 includes this feature in both the Ultimate and Premium editions (and now Professional as well).Bellicose
@Ali parr nice quote , straight way to convince the clientSitwell
I measure my progress, in part by counting lines, but those I remove indicate progress, not those I add.Christenson
Love the quote from Bill Gates. The last person I would ask for programming tips. Actually it's nothing like it at all but just like any other metric it only gives one small piece of the puzzle. If you have 300 user stories to write and the dev mgr says they have written 500 lines of code then you can get a feel that progress is not going well.Decoration
C
98

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.

Coulter answered 4/11, 2013 at 18:18 Comment(8)
Love 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.Coulter
Hard to filter out all generated code (AssemblyInfo etc.) so Analyze/Calculate Code Metrics should be preferred.Nawrocki
Great job, but please mention about the Use Regular Expression checkbox under the Find Options section. It makes it much easierGeminate
@Nawrocki BUT THAT DOESN'T WORK FOR C++Pekingese
A simpler version if no XML, nor HTML... ^(?([^\r\n])\s)*[^\s+?/]+[^\n]*$.Bloodstock
With the "Use Regular Expression" copy/pasting this regex expression produced an error message highlighted in red for me. Any ideas of what i'm doing wrong ? The message was "Invalid regular expression".Oracle
This RegEx worked perfectly for me. Thank you!Lucid
So simple and still works 10 years later. Good job!Amharic
S
82

Found this tip: LOC with VS Find and replace

Not a plugin though if thats what you are looking for.

Shannan answered 28/2, 2010 at 14:27 Comment(4)
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.Fitted
^~(:Wh@//)~(:Wh@\{:Wh@)~(:Wh@\}:Wh@)~(:Wh@\#)~(:Wh@$).+ ended up working better for C#, I was getting some lines consisting of just whitespace.Fitted
Does n't it count all commented lines also? Just lines of CODE please!Berthoud
Here'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))).*$Coulter
P
76

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.

Pascasia answered 7/8, 2009 at 16:31 Comment(2)
This 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 then cloc . in your solution dir. Job done!Papacy
I 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.Danialdaniala
C
45

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,

enter image description here

and select "Calculate metrics"

enter image description here

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

Chiquita answered 14/11, 2012 at 10:45 Comment(9)
Visual Studio 2010 also have this metrics. Actually nothing new in VS2012 at all.Kirkham
Yep, 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.Chiquita
@MikeChaliy May be second introduction sentence has confused you, so I've rewritten it a little bit to avoid such confusion.Chiquita
i have a n-layer solution but that display this error: "Exception has been thrown by the target of an invocation." why?Mere
@Chiquita I disagree with your statement, "no reason to use any extension or tools for it.". If I, as I do, wish to count the lines of code in 500 solution files why would I want to open them individually in VS to view the lines of code. A stand alone tool would be much more efficient.Fatigued
@MichaelEakins Everyone decides for himself, based on concrete situation. I just want to say that that such task could be accomplished without any 3rd party tools. But there are many ways how to achieve it: implement something (script or tool), buy something or use something(e.g. NDepend for more then 500$ or install Sonar) etc. So maybe we should think about it in scope of other more concrete questionChiquita
This is not lines of code, but Compiled Lines (ie after it is turned into IL). I think Fermin was looking for pre compiled lines.Clarettaclarette
If I understand correctly, this will miss XAML, XML, RESX etc.Distributive
I just found out that this tool won't work for C++. It can only analyze managed code.Chinachinaberry
H
30

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@/#).+
Hapsburg answered 1/10, 2013 at 12:20 Comment(0)
G
20

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)

Granuloma answered 7/8, 2009 at 13:51 Comment(2)
Visual Studio Team System 2008 doesn't manage to count unmanaged code. ;)Blaise
This doesn't work with c++ (even in VS 2022).Fiduciary
K
18

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.

Kentigera answered 17/3, 2012 at 17:3 Comment(1)
There is also a version for VS 2012Mcculloch
M
15

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:

Markitamarkka answered 25/4, 2010 at 5:41 Comment(0)
J
13

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.

Jellify answered 31/7, 2020 at 13:51 Comment(2)
Not applicable for C/C++ project. Only available for C# and Visual Basic that they are not website projects or shared projectsDreiser
Also available or Visual Studio 2019/2022 CommunityGomorrah
P
11

You could use:

Photofluorography answered 7/8, 2009 at 13:39 Comment(0)
S
6

I prefer OxyProject Metrics VS Addin.

Satisfactory answered 13/5, 2010 at 14:0 Comment(0)
R
4

Other simple tool For VS2008 (open source): http://www.accendo.sk/Download/SourceStat.zip

Ripley answered 17/1, 2010 at 14:34 Comment(0)
C
4

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}
Carmencarmena answered 22/5, 2013 at 9:5 Comment(0)
I
3

Use Menu-> Analyse - > Calculate Code Metrics option in Visual Studio 2010 Ultimate.

Impede answered 11/7, 2011 at 22:14 Comment(0)
D
3

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."

Dagostino answered 15/4, 2014 at 18:55 Comment(0)
C
2

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

Crum answered 11/3, 2012 at 1:21 Comment(0)
Q
2

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

Quite answered 22/5, 2013 at 9:49 Comment(0)
L
2

You can use free tool SourceMonitor

Gives a lot of measures: Lines of Code, Statement Count, Complexity, Block Depth

Has graphical outputs via charts

Laryngitis answered 8/4, 2014 at 7:16 Comment(0)
B
1

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

Burnt answered 13/5, 2010 at 14:7 Comment(0)
R
1

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

Rohn answered 4/6, 2011 at 7:44 Comment(0)
B
1

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:

https://gist.github.com/1674457

Burushaski answered 25/1, 2012 at 3:18 Comment(0)
S
1

In Visual Studio 2015 go to the Analyze Menu and select "Calculate Code Metrics".

Stickleback answered 28/1, 2017 at 22:45 Comment(1)
This doesn't work for c++ projects (still, as of 2022).Fiduciary
K
1

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 filePattern such 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 != "bin" && dir != "obj" && !dir.EndsWith("Test"),
    "*.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
Katiekatina answered 1/12, 2023 at 4:37 Comment(0)
C
0

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.

HTH



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


Convivial answered 26/11, 2023 at 8:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.