Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Article

Source Code Line Counter

Rate me:
Please Sign up or sign in to vote.
4.56/5 (27 votes)
13 Mar 20073 min read 177.7K   3K   58   38
Complete source code line counter for .cs and .vb files (not an addon)

Sample Image - SourceCode.jpg

Introduction

While updating my cv, I wanted a quick way of seeing how many lines of code my application contained (160,430 lines!). I haven't looked into Visual Studio Add-ins too much so I wrote a simple stand-alone application that has a few nice features.

Using the Application

Fire up the application and select a folder which contains your code or projects - that's it. The application then searches for all code files and counts every line of code. It displays the files included along the line count. It then generates a total at the bottom.

Checking the "Include subfolders" will instruct the software to search all the sub folders, and you also have the option to look for particular source files, *.cs for C# and *.vb for VB.net.

Nice Feature

Some of my projects are spread across two folders, (client / server) so I needed a way of adding these two totals together. After calculating the total for one folder, you can click on the Grouping > Add menu to add the total and directory to a list. As you tally up the folders a total is show in the menu.

Not a lot of Code

There isn't a lot of code to this but here's the important parts.

Using the DirectoryInfo.GetFiles function allows for easy use of searching just a folder or all folders contained within it with a search pattern, *.cs or *.vb. It's fast and saves time having to write your own recursive function.

C#
DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
FileInfo[] files = dir.GetFiles(cmbSearchPattern.SelectedItem.ToString(), 
    (chkIncludeSubfolders.Checked ? SearchOption.AllDirectories : 
    SearchOption.TopDirectoryOnly));

In case you aren't familiar with the inline if statement I hope this makes it a little clearer.

C#
(true_or_false ? Do_this_if_true : Do_this_if_false)
(chkIncludeSubfolders.Checked ? SearchOption.AllDirectories : 
    SearchOption.TopDirectoryOnly));

Counting the lines

I figured that to count the lines I should open the text and use a RegEx "\n" to calculate the lines, but I guess that the RegEx is doing the same thing I would which is open the file and read each line. So I just use a loop to count the lines, which is just as quick I reckon.

C#
reader = file.OpenText();
while (reader.ReadLine() != null)
    {
        fileCounter++;
    }
reader.Close();

Collection.RemoveAt

Got stuck trying to remove items within a collection because I only need to remove a certain amount of items from a particular index. Items 0 to 3 contain the Add, Clear All, Total and a Separator. This solution below sorts this out.

C#
// if there was two items or more in the collection then
//  one item would always be left.
for (int i = 4; i < toolStripGrouping.DropDownItems.Count; i++)
{
    toolStripGrouping.DropDownItems.RemoveAt(i);
}
// this fixes it
int count = toolStripGrouping.DropDownItems.Count;
for (int i = 4; i < count; i++)
{
    toolStripGrouping.DropDownItems.RemoveAt(4);
}

Line Counter Code

The updated line counter code was changed to include or exclude certain lines. The easiest way for me to do this was to first remove the "\t" tabs from the line and then investigate the line of code.

// Replace the tabs
s = s.Replace("\t", "");

// Comment
if (s.StartsWith("//"))
{
    dontCount = true;
}

// Blank line
if (s == "")
{
    dontCount = true;
}

// This autoGenerateCode flag lets the software know that
// it should be looking for the first #endregion to close
// the starting one.
if (autoGeneratedCode)
{
    if (s.Contains("#endregion"))
    {
         dontCount = true;
         autoGeneratedCode = false;
    }
}
else if (s == "#region Windows Form Designer generated code")
{
    dontCount = true;
    autoGeneratedCode = true;
}

History of Searches

I thought that re-browsing projects I have already counted was getting a bit repetitive so adding a history made sense.

Basically it works like this: if a search is performed it checks to see if it exists in the history stored in the ToolStripItems. If it does then it just moves that ToolStripItem to the top using the Insert function with a index set to 0. If it doesn't then it first checks to see if it has reached the maximum amount allowed (currently 5), removing the last one if it has and inserting the new search into index.

C#
private void AddToFolderHistory(string FolderPath)
{
    // Check if folder exists in the list
    ToolStripItem[] searchItems = btnBrowse.DropDownItems.Find(FolderPath, 
        true);
    if (searchItems.Length == 0)
    {
        // Doesn't exist
        if (btnBrowse.DropDownItems.Count == maximumHistory)
        {
            btnBrowse.DropDownItems.RemoveAt(maximumHistory-1);
        }

        ToolStripMenuItem item = new ToolStripMenuItem();
        item.Name = item.Text = FolderPath;
        item.Click += new EventHandler(FolderHistory_Click);
        this.btnBrowse.DropDownItems.Insert(0, item);
    }
    else
    {
        // Does exist so just move to the top
        this.btnBrowse.DropDownItems.Insert(0, searchItems[0]);
    }
}
private void FolderHistory_Click(object sender, EventArgs e)
{
    // History item has been selected so move to the top
    lblFolder.Text = ((ToolStripMenuItem)sender).Text;
    this.btnBrowse.DropDownItems.Insert(0, ((ToolStripMenuItem)sender));
    CountFiles(lblFolder.Text);
}

Conclusion

In my opinion, a neat little application that does exactly what it says on the tin. It's helped with my cv but no job offers just yet!

History

  • Added the ability to not count blank lines, comments, Visual Studio auto-generated code, or designer files. This is accessed through the File Options menu items.

Updated Sample Image - SourceCodeLineMenu.jpg

  • Changed the search routine so that you can browse multiple extensions (*.cs|*.vb) at the same time.
  • Copy the current list of files and number of lines to the clipboard for email/printing
  • Redesigned the Browse feature with a Toolbar
  • Added a Recount button
  • A quick history list of the last 5 (configurable in code) searches - explained below.
  • Add the additional code to filter vb files.

Update Number 2

If someone could send me the "#region" and "#endregion" in C++.net I can add this to the routine as well.

No ASPX just yet. I have a real software job to do.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalline of code... Pin
M i s t e r L i s t e r5-Oct-10 6:25
M i s t e r L i s t e r5-Oct-10 6:25 
GeneralGreat job - needs sorting. Pin
AORD20-Aug-10 10:09
AORD20-Aug-10 10:09 
GeneralSort lines can be done by copying to excel - However probably better to edit code and recomplie. Pin
AORD20-Aug-10 10:01
AORD20-Aug-10 10:01 
GeneralEdit 1 line of code and recomplie - now in MS Excel it is easy to sort. Pin
AORD20-Aug-10 11:01
AORD20-Aug-10 11:01 
GeneralGood tool but just an FYI Pin
sillvor8-Jul-10 8:03
sillvor8-Jul-10 8:03 
Generalfantastic tool Pin
djpitagora6-May-10 12:12
djpitagora6-May-10 12:12 
GeneralNeat little tool Pin
Lawk Salih11-Mar-10 7:16
Lawk Salih11-Mar-10 7:16 
GeneralCode update Pin
albertino callientes14-May-09 7:44
albertino callientes14-May-09 7:44 
GeneralGood article Pin
Donsw18-Jan-09 16:41
Donsw18-Jan-09 16:41 
GeneralGreat job. Pin
Member 347763123-Dec-08 11:40
Member 347763123-Dec-08 11:40 
GeneralCommet with /* to */ Pin
samcreek30-Jun-07 12:05
samcreek30-Jun-07 12:05 
GeneralRe: Commet with /* to */ [modified] Pin
DXNuk23-Jun-08 2:51
DXNuk23-Jun-08 2:51 
Generalusing the tool for Visual Basic 6.0 Pin
Mike A. Fowler24-Feb-07 8:06
Mike A. Fowler24-Feb-07 8:06 
GeneralRe: using the tool for Visual Basic 6.0 Pin
DXNuk24-Feb-07 14:08
DXNuk24-Feb-07 14:08 
GeneralRe: using the tool for Visual Basic 6.0 Pin
Mike A. Fowler26-Feb-07 13:24
Mike A. Fowler26-Feb-07 13:24 
Generalusing the tool for Visual Basic 6.0 Pin
Mike A. Fowler24-Feb-07 8:04
Mike A. Fowler24-Feb-07 8:04 
GeneralEarlier Versions of VB Pin
heron_home17-Sep-06 8:53
heron_home17-Sep-06 8:53 
GeneralRe: Earlier Versions of VB Pin
DXNuk18-Sep-06 0:23
DXNuk18-Sep-06 0:23 
GeneralWhitespace bug Pin
Big Jim12-Sep-06 11:22
Big Jim12-Sep-06 11:22 
GeneralRe: Whitespace bug Pin
DXNuk12-Sep-06 11:42
DXNuk12-Sep-06 11:42 
Generalgood job! Pin
winart11-Sep-06 20:31
winart11-Sep-06 20:31 
GeneralRe: good job! Pin
decoda20-Feb-07 15:43
decoda20-Feb-07 15:43 
GeneralVB source... :) Pin
Big Jim11-Sep-06 18:42
Big Jim11-Sep-06 18:42 
AnswerRe: VB source... :) Pin
DXNuk12-Sep-06 6:25
DXNuk12-Sep-06 6:25 
GeneralRe: VB source... :) Pin
Big Jim12-Sep-06 10:50
Big Jim12-Sep-06 10:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.