0

Ok so I've got a program that needs to read from a text file that looks like this

[Characters]
John
Alex
Ben

[Nationality]
Australian
American
South African

[Hair Colour]
Brown
Black
Red

What I would like to do is only have one method that reads a section depending on the parameter that is passed.

Is this possible and how?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Brendon Rother
  • 119
  • 4
  • 17
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Nov 13 '13 at 03:35
  • What did you try? What are you having trouble with? Are you asking how to open a file? How to read a line? How to loop through lines? How to check for a section? – SLaks Nov 13 '13 at 03:35
  • That looks like an INI file. Why not use an INI file parser? https://github.com/rickyah/ini-parser – Matthew Lock Nov 13 '13 at 03:36

3 Answers3

6
var sectionName = "[Nationality]";
string[] items = 
    File.ReadLines(fileName)                           //read file lazily 
        .SkipWhile(line => line != sectionName)        //search for header
        .Skip(1)                                       //skip header
        .TakeWhile(line => !string.IsNullOrEmpty(line))//take until next header
        .ToArray();                                    //convert to array

items will have :

Australian 
American 
South African 
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
2

You can do it with LINQ like this:

var sectionCharacters = File.ReadLines(@"c:\myfile.txt")
    .SkipWhile(s => s != "[Characters]") // Skip up to the header
    .Skip(1)                             // Skip the header
    .TakeWhile(s => s.Length != 0)       // Take lines until the blank
    .ToList();                           // Convert the result to List<string>
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

I know that it's not the best way to do that, but it'll be easier for you like that if you just started programming. And by adding few additional lines of code to this, you can make a method that would extract specific chunk from your text file.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(ExtractLine("fileName.txt", 4));
        Console.ReadKey();
    }

    static string ExtractLine(string fileName, int line)
    {
        string[] lines = File.ReadAllLines(fileName);

        return lines[line - 1];
    }
}
martynaspikunas
  • 485
  • 5
  • 15