edgarmtze
edgarmtze

Reputation: 25038

How to read specific part of txt

Supposing I have a txt file like:

%Title
%colaborations                 Destination
1                              123
2                              456
3                              555
%my name                       Destination
Joe doe $re                    Washington
Marina Panett $re              Texas
..
Laura Sonning $mu              New York
%other stuff

How can I save in array

array{
      ("Joe doe $re"), 
      ("Marina Panett $re"),
     ...,
      ("Laura Sonning $mu")
    }

As I need to skip:

%Title
%colaborations                 Destination
1                              123
2                              456
3                              555

until I find

%my name                       Destination

I would start reading until end of file or I find something with "%"

I was thinking to use string txt = System.IO.File.ReadAllText("file.txt"); but I do not think is a good idea to read all txt as I only need some parts...

Upvotes: 1

Views: 241

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460028

You could use Enumerable.SkipWhile until you find what you are looking for:

string[] relevantLines = File.ReadLines(path)
    .SkipWhile(l => l != "%my name                       Destination")
    .Skip(1)
    .TakeWhile(l =>!l.StartsWith("%"))
    .ToArray();

Note that File.ReadLines does not need to read the whole file. It's similar to a StreamReader.

Upvotes: 3

John Ryann
John Ryann

Reputation: 2393

read each line, once the line contains "%my name" then split the line by space.

Upvotes: 1

Related Questions