1

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

edgarmtze
  • 24,683
  • 80
  • 235
  • 386
  • 2
    Accessing a file always has to go sequential: start from the beginning and go to where you find the data you need (files don't allow random access). Just keep looping trough the lines until you have one that starts with `%`. – Jeroen Vannevel Sep 20 '13 at 22:07
  • There's no way to skip ahead when reading a file. – System Down Sep 20 '13 at 22:08
  • 1
    Look at -> http://stackoverflow.com/questions/12856471/c-sharp-search-string-in-txt-file – gleng Sep 20 '13 at 22:08
  • possible duplicate of [How to read a specific part in text file?](http://stackoverflow.com/questions/11251670/how-to-read-a-specific-part-in-text-file) –  Sep 20 '13 at 22:08
  • Realistically you are going to have to stream line by line in case the file is large. I would read line by line with a Stream Reader then use pattern matching on each line to extract the apropriate information. – jcwrequests Sep 20 '13 at 22:24

2 Answers2

3

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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

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

John Ryann
  • 2,283
  • 11
  • 43
  • 60