Brendon Rother
Brendon Rother

Reputation: 119

Read specific line in text file

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?

Upvotes: 0

Views: 4077

Answers (3)

martynaspikunas
martynaspikunas

Reputation: 515

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];
    }
}

Upvotes: 1

Ilya Ivanov
Ilya Ivanov

Reputation: 23646

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 

Upvotes: 6

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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>

Upvotes: 2

Related Questions