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

时间:2012-10-12 09:51:58

标签: c#

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

示例:

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

我需要细节与他们合作。

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

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

但是现在我一直在阅读行(数据),直到“CustomerCh”来提取细节。

5 个答案:

答案 0 :(得分:16)

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

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 :(得分:9)

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

答案 2 :(得分:4)

使用LINQ,您可以使用SkipWhile / TakeWhile方法,如下所示:

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

答案 3 :(得分: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];
   }
}

答案 4 :(得分: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);