[ Count all of the Lines of Code in a C#.NET Application ]

By: Daniel S. Soper


The source code below demonstrates how to count all of the lines of code that comprise a C#.NET program. This code applies to C# programs written using Visual Studio 2005, but can be easily adapted to other environments.

This code works by finding all of the source code (*.cs) files in your application's root folder and level-1 subfolders. A stream reader is then used to count the lines of code in each source code file.

Here's the C# source code... Only 40 lines (including comments)!

/// 
/// This code counts all of the lines of code that comprise a C#.NET
/// application.
/// USAGE: Paste the static 'CountLinesOfCode()' method into your
///        application's 'Program' class, and call it from anywhere
///        in the application.
/// IMPORTANT: The 'CountLinesOfCode()' method requires the 'System.IO'
///            namespace and the 'System.Collections' namespace!
/// ******************************************************************
///  AUTHOR: Daniel S. Soper
///     URL: http://www.danielsoper.com
///    DATE: 22 December 2007
/// LICENSE: Public Domain. Enjoy!   :-)
/// ******************************************************************
/// 
private static int CountLinesOfCode()
{ //counts the total lines of code that comprise this application
    ArrayList folders = new ArrayList();
    ArrayList files = new ArrayList();
            
    //find all C# source code files in the application's root folder & level-1 subfolders
    DirectoryInfo di = new DirectoryInfo(Application.StartupPath.Substring(0, Application.StartupPath.Length - 9));
    folders.Add(di);
    folders.AddRange(di.GetDirectories());
    foreach (DirectoryInfo di2 in folders) files.AddRange(di2.GetFiles("*.cs"));
    int lines = 0;
    StreamReader sr;
    foreach (FileInfo fi in files)
    { //for each C# source code file
        sr = new StreamReader(fi.FullName);
        while (!sr.EndOfStream)
        {
            sr.ReadLine();
            lines++;
        } //end while
        sr.Close();
    } //end foreach

    return lines;
} //end CountLinesOfCode method
			

Click here to return to the Free Programming Resources index

Click here to return to DanielSoper.com