Lines of Code
Below is the complete code for the Lines of Code Try It Out! problem.
The StringExtensions Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethods
{
/// <summary>
/// A place to put extension methods for the string type.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Counts the number of words in a string and returns it.
/// </summary>
public static int WordCount(this string text)
{
return text.Split(' ').Length;
}
/// <summary>
/// Counts the number of sentences in a string. Note that this
/// is definitely an oversimplification, as there are other uses
/// for the '.' character than ending sentences. This method
/// ignores ellipses that are represented as "...".
/// </summary>
public static int SentenceCount(this string text)
{
text = text.Replace("...", "");
return text.Split('.').Length;
}
/// <summary>
/// Counts the number of paragraphs in a string. Paragraphs
/// are assumed to be delimited by the new line character
/// ('\n').
/// </summary>
public static int ParagraphCount(this string text)
{
return text.Split('\n').Length;
}
}
}
The Program Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ExtensionMethods
{
class Program
{
static void Main(string[] args)
{
string directory = "C:/Full/Path/Of/Directory/Here";
Console.WriteLine(CountLinesOfCode(directory));
Console.ReadKey();
}
/// <summary>
/// Totals up all of the lines of code in all of the files in a
/// particular directory. This method is used recursively, so
/// any directory contained within this directory will be counted
/// up by another call to this method.
/// </summary>
/// <param name="directory"></param>
/// <returns></returns>
public static int CountLinesOfCode(string directory)
{
// Start at 0.
int count = 0;
// Go through each child directory that is contained within
// this directory and add up their lines of code.
foreach (string child in Directory.GetDirectories(directory))
{
count += CountLinesOfCode(child);
}
// Go through each file in this directory...
foreach (string file in Directory.GetFiles(directory))
{
// ... and if they're a .cs file...
if (file.EndsWith(".cs"))
{
// include the number of lines in that file.
count += CountLinesOfCodeInFile(file);
}
}
return count;
}
/// <summary>
/// Counts the number of lines in a file. This does not account
/// for blank lines or lines that are just comments.
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static int CountLinesOfCodeInFile(string file)
{
return File.ReadAllText(file).ParagraphCount();
// or alternatively...
// return File.ReadAllLines(file).Length;
}
}
}