c#在txt文件中搜索字符串

nuk*_*eos 17 c#

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

例:

CustomerEN //search for this string
...
some text wich has details about customer
id "123456"
username "rootuser"
...
CustomerCh //get text till this string
Run Code Online (Sandbox Code Playgroud)

我需要细节与他们合作.

我正在使用linq来搜索"CustomerEN",如下所示:

File.ReadLines(pathToTextFile).Any(line => line.Contains("CustomerEN"))
Run Code Online (Sandbox Code Playgroud)

但现在我仍然坚持阅读行(数据)直到"CustomerCh"来提取细节.

Raw*_*ing 19

如果您的线对只在文件中出现一次,则可以使用

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

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

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);
}
Run Code Online (Sandbox Code Playgroud)


Ekk*_*Ekk 10

你必须使用,while因为foreach不知道索引.下面是一个示例代码.

int counter = 0;
string line;

Console.Write("Input your search text: ");
var text = Console.ReadLine();

System.IO.StreamReader file =
    new System.IO.StreamReader("SampleInput1.txt");

while ((line = file.ReadLine()) != null)
{
    if (line.Contains(text))
    {
        break;
    }

    counter++;
}

Console.WriteLine("Line number: {0}", counter);

file.Close();

Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)