简体   繁体   中英

c# streamreader textfiles read line before/after

In some special cases, I need some lines before and after the current position. Eg

public 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 needed.

Is there an easy way to do this?

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.

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.

        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() 
            };

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM