Myslatron
Myslatron

Reputation: 47

C# Reading parts of txt file

I have txt file that I get from software that looks like this.

----------------------------------------------------------------------------
XXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXX
----------------------------------------------------------------------------

XXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXX

-- YYYYYYYYYYYYYY ----------------------------------------------------------
XXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXX

-- YYYYYYYYY ---------------------------------------------------------------
 (1) AAAAAAAAAAAAAA
 (2) BBBBBBBBBBBBBB
 (3) CCCCCCCCCCCCCC

----------------------------------------------------------------------------
 (1) AAAAAAAAAAAAAA
----------------------------------------------------------------------------
           Model : AAAAAAAAAAAAAA
        Firmware : XXXXXXXXXXXXXX
   Serial Number : 00000000000000
       Disk Size : 999 GB

-- XXXXXXXXXX --------------------------------------------------------------

And I need to read data only from this section:

----------------------------------------------------------------------------
 (1) AAAAAAAAAAAAAA
----------------------------------------------------------------------------
           Model : AAAAAAAAAAAAAA
        Firmware : XXXXXXXXXXXXXX
   Serial Number : 00000000000000
       Disk Size : 999 GB

-- XXXXXXXXXX --------------------------------------------------------------

I have tried StreamReader like this:

StreamReader sw = new StreamReader(txtFile);
while (!sw.EndOfStream)
{
    string line = sw.ReadLine();
    if (line.Contains("(1)"))
    {
        OtherFunction(line);
    }
}
sw.Close();

But that doesn't work well. I cannot use some function that would read only from for example line 20 to line 23. I need something to say to the SteamReader that he has to read from line that contains ------------------ to line that contains -- XXXXXXXXXX ----

Any help would be greatly apriciated. Thanks!

Upvotes: 0

Views: 99

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You can try Linq and query for required lines, something like this:

using System.IO;
using System.Linq;

...

var lines = File
  .ReadLines(txtFile)
  .SkipWhile(line => !line.Contains("(1)"))         // Skip all lines before "...(1)..." 
  .SkipWhile(line => !line.Contains("-------------------")) // -/- "----"
  .Skip(1)                                          // Skip "----" itself
  .TakeWhile(line => !line.Contains("XXXXXXXXXX"))  // Take all lines before "...XXXXXX..."
  .ToArray();                                       // Have lines as an array 

Upvotes: 3

Alex Leo
Alex Leo

Reputation: 2851

Instead of a StreamReader, I would use File.ReadAllLines() which returns an array of strings.

You can then traverse the array until you find the desired result extract and continue. Eg:

var lines = File.ReadLines(txtFile);

Upvotes: 0

Related Questions