c#在txt文件中搜索字符串 [英] c# search string in txt file

查看:22
本文介绍了c#在txt文件中搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果字符串比较,我想在 txt 文件中找到一个字符串,它应该继续读取行直到我用作参数的另一个字符串.

I want to find a string in a txt file if string compares, it should go on reading lines till another string which I'm using as parameter.

示例:

CustomerEN //search for this string
...
some text which has details about the customer
id "123456"
username "rootuser"
...
CustomerCh //get text till this string

否则我需要详细信息才能与他们合作.

I need the details to work with them otherwise.

我正在使用 linq 搜索CustomerEN";像这样:

I'm using linq to search for "CustomerEN" like this:

File.ReadLines(pathToTextFile).Any(line => line.Contains("CustomerEN"))

但现在我一直在阅读行(数据)直到CustomerCh";提取详细信息.

But now I'm stuck with reading lines (data) till "CustomerCh" to extract details.

推荐答案

如果你的这对线在你的文件中只会出现一次,你可以使用

If your pair of lines will only appear once in your file, you could use

File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .Skip(1) // optional
    .TakeWhile(line => !line.Contains("CustomerCh"));

如果您可以在一个文件中多次出现,您可能最好使用常规的 foreach 循环 - 读取行,跟踪您当前是在客户内部还是外部等:

If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:

List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
    if (line.Contains("CustomerEN") && current == null)
        current = new List<string>();
    else if (line.Contains("CustomerCh") && current != null)
    {
        groups.Add(current);
        current = null;
    }
    if (current != null)
        current.Add(line);
}

这篇关于c#在txt文件中搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆