Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

September 25, 2009

Count Lines Of Code

Filed under: C#,Text Files,VB.NET @ 7:34 pm

The number of lines of code is not a very useful metric for evaluating good code or a good developer. However, it is sometimes useful to know how much code you have.

For example, I recently worked on a project converting a VB 6 application to .NET. When we were finished, it was interesting to see how we had reduced the number of lines of code by 50% and yet added functionality.

There are tools available to help you get counts. But if you just want a quick and dirty technique, here is some code.

NOTE: Be sure to import System.IO.

In C#:

public class LineCount
{
    private Dictionary<string, int> _FilesInProject =
                                      new Dictionary<string, int>();
    public Dictionary<string, int> FilesInProject
    {
        get { return _FilesInProject; }
    }

    public int GetLineCount(string directoryName,
                            string[] fileExtensions)
    {
        int LineCount = 0;
        int TotalLineCount = 0;

        DirectoryInfo topDirectoryInfo =
                                new DirectoryInfo(directoryName);

        // Process the directory and all subdirectories
        foreach (DirectoryInfo dir in
                                topDirectoryInfo.GetDirectories())
        {

            // Loop the file types
            foreach (string fileExtension in fileExtensions)
            {

                foreach (FileInfo file in dir.GetFiles(fileExtension))
                {
                    // open files for streamreader
                    StreamReader sr = new StreamReader(file.FullName);
                    //loop until the end
                    while ((sr.ReadLine() != null))
                    {
                        LineCount += 1;
                    }
                    //close the streamreader
                    sr.Close();

                    // add the file name to the list
                    FilesInProject.Add(file.FullName, LineCount);

                    // Handle the line counting
                    TotalLineCount += LineCount;
                    LineCount = 0;
                }
            }
        }

        return TotalLineCount;
    }
}

In VB:

Public Class LineCount

    Private _FilesInProject As New Dictionary(Of String, Integer)
    Public ReadOnly Property FilesInProject() _
                                As Dictionary(Of String, Integer)
        Get
            Return _FilesInProject
        End Get
    End Property

    Public Function GetLineCount(ByVal directoryName As String, _
                        ByVal fileExtensions() As String) As Integer
        Dim LineCount As Integer = 0
        Dim TotalLineCount As Integer = 0

        Dim topDirectoryInfo As New DirectoryInfo(directoryName)

        ‘ Process the directory and all subdirectories
        For Each dir As DirectoryInfo In _
                                topDirectoryInfo.GetDirectories

            ‘ Loop the file types
            For Each fileExtension As String In fileExtensions

                For Each file As FileInfo In _
                                   dir.GetFiles(fileExtension)
                    ‘ open files for streamreader
                    Dim sr As New StreamReader(file.FullName)
                    ‘loop until the end
                    While Not (sr.ReadLine() Is Nothing)
                        LineCount += 1
                    End While
                    ‘close the streamreader
                    sr.Close()

                    ‘ add the file name to the list
                    FilesInProject.Add(file.FullName, LineCount)

                    ‘ Handle the line counting
                    TotalLineCount += LineCount
                    LineCount = 0
                Next
            Next
        Next

        Return TotalLineCount
    End Function
End Class

This code counts the number of lines in each file and retains a total count. It stores the names of the files and the line count for each file in a dictionary. It returns the total count as the return value from the function. If you only need the total count, you can remove the Dictionary.

The LineCount class has one read-only property (FilesInProject) that defines the files within a specified directory along with each files line count. The file name is stored as the key and the file count as the value in each dictionary entry.

The GetLineCount method takes a directory name and a set of file extensions. All files in all directories and subdirectories with any of the defined extensions will be found and counted.

The code uses the DirectoryInfo class to loop through the directories. It then uses the FileInfo class to get the files with the defined extensions.

For each found file, it uses a StreamReader to read the file and count the lines.

You can make this method fancier by adding additional code before counting the line. For example, you could skip blank lines, or lines with comments, or lines with just { or }. This simple case just counts all of the lines.

The code stores each found file along with its line count into the dictionary. It also accumulates the total line count.

When it is finished, it returns the total line count.

You can use this class like this:

In C#:

string[] fileExtensions  = {"*.cs"};
string directoryName  = @"C:\Tools\SampleApplication";

LineCount lc = new LineCount();
int totalLines  =
    lc.GetLineCount(directoryName, fileExtensions);

foreach (KeyValuePair<string,int> f in lc.FilesInProject)
    Debug.WriteLine(f.Key + ": " + f.Value);
Debug.WriteLine("Total: " + totalLines);

In VB:

Dim fileExtensions() As String = {"*.vb"}
Dim directoryName As String = "C:\Tools\SampleApplication"

Dim lc As New LineCount
Dim totalLines As Integer = _
    lc.GetLineCount(directoryName, fileExtensions)

For Each f In lc.FilesInProject
    Debug.WriteLine(f.Key & ": " & f.Value)
Next
Debug.WriteLine("Total: " & totalLines)

This code sets up an array of file extensions. In this example, only one extension is included in the array. The code then sets up the directory to search.

The code then calls the GetLineCount and then loops through the resulting Dictionary to list the found files and their line counts.

Enjoy!

6 Comments

  1.   Bernard Londeix — September 26, 2009 @ 5:05 am    Reply

    Hello Deborah,
    Welcome to the metrics world. You have just demonstrated that the functionality, what is useful to the user, is not the programming language but what is hiding behind the language (i.e. the IDE and the OS) and how the language is used by the programmer.
    I bet that, had you measured the functionality with COSMIC (www.cosmicon.com) you would have found the same number for VB6 as for .NET. This is because COSMIC measures the functionality and not the lines of code.
    This being said I like your code, I’ll try it.
    Best regards,
    Bernard Londeix
    Telmaco Ltd (www.telmaco.com)

  2.   JL — September 26, 2009 @ 9:33 am    Reply

    Please explain:
    // Process the directory and all subdirectories

    in the C# program,
    it seems to me that only the subdirectories are processed.
    If *.cs programs are in the top directory, they will not be added.

    Thanks

  3.   Rich Quackenbush — September 29, 2009 @ 10:53 pm    Reply

    Also, there are some tools built into Visual Studio 2008 that will give you this (and much more information):

    http://blogs.msdn.com/fxcop/archive/2007/10/03/new-for-visual-studio-2008-code-metrics.aspx

    Of course, this will only work for .NET projects.

  4.   DeborahK — September 29, 2009 @ 11:56 pm    Reply

    Hey Rich!
    Good to hear from you. Thanks for pointing to this link. There are some really nice tools there.

    One note on the tool you mentioned …. I believe that it is only available in Visual Studio Team Editions.

    Thanks again!

  5.   Greg — October 5, 2009 @ 9:02 am    Reply

    Here is a 2 liner for it
    wc.exe *.cs
    wc.exe *.vb

    This is on many platforms unix, linux, win32…

    WC(1) User Commands WC(1)

    NAME
    wc – print the number of newlines, words, and bytes in files

    SYNOPSIS
    wc [OPTION]… [FILE]…

    DESCRIPTION
    Print newline, word, and byte counts for each FILE, and a total line if
    more than one FILE is specified. With no FILE, or when FILE is -, read
    standard input.

    -c, –bytes
    print the byte counts

    -m, –chars
    print the character counts

    -l, –lines
    print the newline counts

    -L, –max-line-length
    print the length of the longest line

    -w, –words
    print the word counts

    –help display this help and exit

    –version
    output version information and exit

  6.   Marilee — August 13, 2011 @ 3:59 pm    Reply

    I rckeon you are quite dead on with that.

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs