tags:

views:

47

answers:

3

Hi,

in some some special cases i need some lines before and after the current position

e.g.

pubic string[] getLines(string value, int linesBefore, int linesAfter){

    _streamReader = new StreamReader("file.tmp");
    string[] returnValue;

    string line =  _streamReader.ReadLine();
    while (Line.instr() < 0)
    {
       Line = _streamReader.ReadLine();
    }

    returnValue = READ "value linesBefore"
                + Line // Current Line
                + READ "value linesAfter"
}

Last 3 lines are what i need.

Is there an easy way to do this?

Thank you,

Stefan

A: 

If your file isn't too large, you could just read the whole file and store each line into a List<String> and then grab the last three lines. If your file is really large, use the Queue class -- push the lines into the queue and call TrimToSize to keep it at the number of lines required. Of course, to get the "line after" you'd have to read one more line.

Patrick Steele
A: 

You could keep a copy of the previous line in the loop, and then use an addition ReadLine() after the loop.

pubic string[] getLines(string value, int linesBefore, int linesAfter){ 

_streamReader = new StreamReader("file.tmp"); 
string[] returnValue;

string Line =  _streamReader.ReadLine(); 
string prevLine;
while (Line.instr() < 0) 
{ 
   prevLine = Line;
   Line = _streamReader.ReadLine(); 
} 

string postLine = _streamReader.ReadLine();

returnValue = prevLine + Line + postLine;
} 

If you want multiple lines before/after, create a "rolling" array for prevLines and a while loop to store the postLines in an array using more ReadLine calls.

Jess
A: 
        using (StreamReader _streamReader = new StreamReader("file.tmp"))
        {
            string[] returnValue;

            string previousLine = null;
            string line = _streamReader.ReadLine();
            while (line.instr() < 0)
            {
                previousLine = line;
                line = _streamReader.ReadLine();
            }

            string[] returnValue = new string[] { 
                previousLine, 
                line, 
                _streamReader.ReadLine() 
            };

        }
Erv Walter