简体   繁体   中英

C# StreamReader, Seek backwards for one line from middle of file

Does anyone know how to seek to one previous line when using StreamReader, but I have lines with different length?

I have large txt file, over dozens of GBs, and I need to read it backward for one line from middle.

Thanks.

You can use "File.ReadAllLines" function, this is the fastest way I know to read text file. For example, I have a text file like below.

aaa123
aaa456
aaa789
bbb123
bbb456
bbb789

When I search in each lines in text file if I found "a789". So I expect to get the data of previous line. In this case is "aaa456".

   string[] lines = File.ReadAllLines(@"C:\Users\Binh\Desktop\C#\test\test.txt");           
   string data = "";

   for (int i = 0; i < lines.Length; i++)           
   {
      if(lines[i].Contains("a789"))
      {
          data = lines[i - 1];//Read backward for one line
      }
   }        
   Console.WriteLine(data);//This will return "aaa456"

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