Read specific line in text file

眉间皱痕 提交于 2019-12-10 12:02:24

问题


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?


回答1:


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 



回答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>



回答3:


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


来源:https://stackoverflow.com/questions/19944756/read-specific-line-in-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!