在txt文件中搜索字符串的C#方法

27
我希望在一个txt文件中查找字符串。如果匹配到了这个字符串,它应该继续读取行,直到另一个我用作参数的字符串出现。
例如:
CustomerEN //search for this string
...
some text which has details about the customer
id "123456"
username "rootuser"
...
CustomerCh //get text till this string

否则,我需要详细了解它们的细节。

我正在使用 LINQ 来搜索“CustomerEN”,如下所示:

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

但现在我只能阅读行(数据),直到“CustomerCh”以提取详细信息。

5个回答

33

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

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

如果您在一个文件中可能有多个实例,最好使用普通的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);
}

1
如果您需要不区分大小写的搜索,请查看https://dev59.com/D3RB5IYBdhLWcg3w-8Lo。 - Alexei Levenkov

14

你必须使用 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();

你实际上不需要知道索引。 - Rawling
他需要找到第一个字符串,该字符串仅在其他关键字之后出现。 - Anton Sizikov
如果你想的话,你完全可以把计数器也放在 foreach 循环中。 - Chris
1
每个提出的其他解决方案都会将整个文件读入内存并保留在那里,直到搜索完成。这是唯一一个在执行搜索时使用流仔细管理内存的解决方案。 - Cdaragorn

4

使用 LINQ,您可以像这样使用 SkipWhile / TakeWhile 方法:

var importantLines = 
    File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .TakeWhile(line => !line.Contains("CustomerCh"));

2

如果你只想要第一个字符串,可以使用简单的for循环。

var lines = File.ReadAllLines(pathToTextFile);

var firstFound = false;
for(int index = 0; index < lines.Count; index++)
{
   if(!firstFound && lines[index].Contains("CustomerEN"))
   {
      firstFound = true;
   }
   if(firstFound && lines[index].Contains("CustomerCh"))
   {
      //do, what you want, and exit the loop
      // return lines[index];
   }
}

0

我稍微修改了Rawling在这里发布的方法,以便在同一文件中查找多行直到结尾。这是对我有效的方法:

                foreach (var line in File.ReadLines(pathToFile))
                {
                    if (line.Contains("CustomerEN") && current == null)
                    {
                        current = new List<string>();
                        current.Add(line);
                    }
                    else if (line.Contains("CustomerEN") && current != null)
                    {
                        current.Add(line);
                    }
                }
                string s = String.Join(",", current);
                MessageBox.Show(s);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接