简体   繁体   English

如何阅读txt的特定部分

[英]How to read specific part of txt

Supposing I have a txt file like: 假设我有一个txt文件,如:

%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"); 我当时想用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... 但我不认为阅读所有txt是一个好主意,因为我只需要一些部分......

You could use Enumerable.SkipWhile until you find what you are looking for: 您可以使用Enumerable.SkipWhile直到找到您要查找的内容:

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. 请注意, File.ReadLines不需要读取整个文件。 It's similar to a StreamReader . 它类似于StreamReader

读取每一行,一旦该行包含“%my name”,然后按空格分割。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM