簡體   English   中英

C#StreamReader文本文件讀取之前/之后的行

[英]c# streamreader textfiles read line before/after

在某些特殊情況下,我需要在當前位置之前和之后添加一些行。 例如

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"
}

最后三行是我需要的。

是否有捷徑可尋?

如果文件不是太大,則可以讀取整個文件並將每行存儲到List<String> ,然后獲取最后三行。 如果文件確實很大,請使用Queue類-將行壓入隊列並調用TrimToSize使其保持在所需的行數。 當然,要獲得“之后”,您必須再讀一行。

您可以在循環中保留前一行的副本,然后在循環后使用附加的ReadLine()。

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

如果您希望前后有多行,請為prevLines創建一個“滾動”數組,並創建一個while循環,以使用更多ReadLine調用將postLine存儲在數組中。

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

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM