FileInfo - CountLines

Gets the total number of lines in a file.

Try it

public static string FileName = "test.txt";

public static void Main()
{
	SaveFile();
	
	// C# Extension Method: FileInfo - CountLines
	var count = FileName.ToFileInfo().CountLines();
	
	Console.WriteLine("Number of lines: {0}", count);
}

private static void SaveFile()
{
	var html =
    @"<!DOCTYPE html>
<html>
<body>
<h1>This is <b>bold</b> heading</h1>
<p>This is <u>underlined</u> paragraph</p>
<h2>This is <i>italic</i> heading</h2>
</body>
</html> ";
	
	html.SaveAs(FileName);
}

View Source

using System;
using System.IO;
using System.Linq;

public static partial class Extensions
{
    /// <summary>Gets the total number of lines in a file. </summary>
    /// <param name="this">The file to perform the count on.</param>
    /// <returns>The total number of lines in a file. </returns>
    public static int CountLines(this FileInfo @this)
    {
        return File.ReadAllLines(@this.FullName).Length;
    }

    /// <summary>Gets the total number of lines in a file that satisfy the condition in the predicate function.</summary>
    /// <param name="this">The file to perform the count on.</param>
    /// <param name="predicate">A function to test each line for a condition.</param>
    /// <returns>The total number of lines in a file that satisfy the condition in the predicate function.</returns>
    public static int CountLines(this FileInfo @this, Func<string, bool> predicate)
    {
        return File.ReadAllLines(@this.FullName).Count(predicate);
    }
}