Skip to content

Instantly share code, notes, and snippets.

@lucasloss
Created December 19, 2019 22:19
Show Gist options
  • Select an option

  • Save lucasloss/31d725f4de19985498387de7d3c069c1 to your computer and use it in GitHub Desktop.

Select an option

Save lucasloss/31d725f4de19985498387de7d3c069c1 to your computer and use it in GitHub Desktop.
System.IO.StreamReader extension methods.
using System;
using System.IO;
namespace ExtensionMethods
{
/// <summary>
/// <see cref="StreamReader"/> extension methods.
/// </summary>
public static class StreamReaderExtensions
{
/// <summary>
/// Gets the number of lines of the stream.
/// </summary>
/// <param name="reader">The <see cref="StreamReader"/>.</param>
/// <returns>The number of lines of the stream.</returns>
public static int CountLines(this StreamReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
int count = 0;
long previousPosition = reader.BaseStream.Position;
reader.BaseStream.Position = 0;
reader.DiscardBufferedData();
while (reader.ReadLine() != null)
{
count++;
}
reader.BaseStream.Position = previousPosition;
return count;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment