Half of my day at work was spent trying to locate a bug in a 1,996 line source file… which got me thinking… Just how many lines of code are in this application anyway?
Turns out there are 214649 lines of code, which is 4769 pages worth of code at my editor setting of 45 lines of code per page. That’s just far too much code! Since there’s no built-in functionality to count the lines of code in a project, I decided that it was time to write a command-line utility that I could reuse.
This was much simpler than I thought it would be, with a short recursive function that first loops through the directories, and then through the files in each folder.
First, we loop through the directories inside the current folder and call our function recursively:
foreach(DirectoryInfo subdir in theDirectory.GetDirectories())
{
count += GetLineCount(subdir);
}
Then we loop through an array of file types, because we don’t want to just read any file, as we might get a binary file or something else unusable:
foreach(string filetype in new string[]{ “*.cs“,”*.aspx“, “*.ascx“,”*.xml“,”*.asax“,”*.config“,”*.js“})
{
Now we get to the actual line counting code:
FileInfo[] files = theDirectory.GetFiles(filetype);
foreach(FileInfo thefile in files)
{
StreamReader sr = File.OpenText(thefile.FullName);
while(sr.ReadLine()!=null)
{
count++;
}
}
Here, we are just using a loop around the ReadLine() function, even though we aren’t processing any of the data, we can increment the counter.
To call this function, you would use something like this to pass in the initial directory. You could also modify it to accept the directory on the commandline, but that seemed like overkill for what I wanted it for.
int count = GetLineCount(new DirectoryInfo(Directory.GetCurrentDirectory()));
And this is the source listing for the function:
/// <summary>
/// Recursive function to get the number of lines of code
/// </summary>
/// <param name=”theDirectory”></param>
/// <returns></returns>
public int GetLineCount(DirectoryInfo theDirectory)
{
// Set the initial count to zero
int count = 0;
// Loop through the subdirectories and run this function recursively
foreach(DirectoryInfo subdir in theDirectory.GetDirectories())
{
count += GetLineCount(subdir);
}
// Loop through each file type we are checking
foreach(string filetype in new string[]{ “*.cs“,”*.aspx“, “*.ascx“,”*.asax“,”*.xml“,”*.config“,”*.js“})
{
// Get the list of each file of the particular file type
FileInfo[] files = theDirectory.GetFiles(filetype);
foreach(FileInfo thefile in files)
{
// Open the file, figure out how many lines there are and update the count
StreamReader sr = File.OpenText(thefile.FullName);
while(sr.ReadLine()!=null)
{
count++;
}
}
}
return count;
}
You can download the utility here. Running the utility in any folder will count the lines of code for that folder and folders beneath it.
LineCount 0.1 Command-Line Utility
LineCount 0.1 Source