在文本文件中搜索字符串,如果找到,则读取下一行

Search for a string in text file, if found, read the next line

我显然是 C# 新手。

我正在寻找一种方法来读取文本文件中的每一行并在该文本文件中搜索唯一的字符串。如果找到字符串,那么我只需要它读取下一行并将其输出到文本框。

如有任何帮助,我们将不胜感激。

您可以逐行枚举,直到找到唯一的字符串并将下一行设置为文本框值并中断操作

bool found = false;
foreach (var line in File.ReadLines("filepath"))
{
    if (found)
    {
        textBox1.Text = line;
        break;
    }
    found = line.Contains("unique string");                
}
textBox1.Text = "not found";

File.ReadLines(file) 逐行读取指定文件中的行。

foreach(var item in container) 将从它的容器中一件一件地取出物品,你可以用物品做你的事情。

y.Contains(x) 检查 y 是否包含 x。

与其他答案类似,但这涉及 StreamReader class:

using (StreamReader r = new StreamReader("filename.ext"))
{
    string line, version = "";
    bool nameFound = false;
    while ((line = r.ReadLine()) != null)
    {
        if (nameFound)
        {
            version = line;
            break;
        }

        if (line.IndexOf("UniqueString") != -1)
        {
            nameFound = true;
            // current line has the name
            // the next line will have the version
        }
    }

    if (version != "")
    {
        // version variable contains the product version
    }
    else
    {
        // not found
    }
}