Is there a C # equivalent for Java LineNumberReader?

Is there a C # equivalent for Java LineNumberReader ?

i.e. a StreamReader.ReadLine(), which counts the line number. Or is this the only way to achieve this by creating a custom subclass of StreamReader and implementing the necessary count in an overridden method?

+3
source share
2 answers

There is no direct equivalent in the .NET Framework.

, , TextReader TextReader, TextReader (StreamReader, StringReader).

, TextReader.Read TextReader.Peek. TextReader.

class LineNumberTextReader : TextReader
{
    private readonly TextReader reader;
    private int b;
    private int line;

    public LineNumberTextReader(TextReader reader)
    {
        if (reader == null) throw new ArgumentNullException("reader");
        this.reader = reader;
    }

    public int Line
    {
        get { return this.line; }
    }

    public override int Peek()
    {
        return this.reader.Peek();
    }

    public override int Read()
    {
        int b = this.reader.Read();
        if ((this.b == '\n') || (this.b == '\r' && b != '\n')) this.line++;
        return this.b = b;
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing) this.reader.Dispose();
    }
}
+3

. StreamReader:

public class CustomStreamReader : StreamReader
{
    private int _lineNumber  = 0;

    public CustomStreamReader(Stream stream)
        : base(stream)
    {
    }

    public int LineNumber 
    { 
        get 
        {
            return _lineNumber;
        } 
    }

    public override string ReadLine()
    {
        _lineNumber++;
        return base.ReadLine();
    }
}

, , Stream, ReadLine(). , , LineNumber .

+1

Source: https://habr.com/ru/post/1774842/


All Articles