ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

Tail

Set the stream position to the place where for example 10 lines will be returned when read to end.

Source

public static class StreamExtensions
{
    /// <summary>
    /// Set position to return n number of lines
    /// </summary>
    /// <param name="this"></param>
    /// <param name="n">number of lines</param>
    /// <returns>The stream with position set</returns>
    public static Stream Tail(this Stream @this, int n)
    {
        if (@this.Length == 0)
            return @this;
        @this.Seek(0, SeekOrigin.End);
        var count = 0;
        while (count <= n)
        {
            @this.Position--;
            var c = @this.ReadByte();
            @this.Position--;
            if (c == '\n')
            {
                ++count;
            }
            if (@this.Position == 0)
                break;

        }
        return @this;
    }
}

Example

var s = File.OpenFile("text.txt");
s.Tail(10);

Author: smolesen

Submitted on: 29 dec 2011

Language: C#

Type: System.IO.Stream

Views: 3110