StreamReader 读取包含的最后一行

StreamReader read last line that contains

我试图从一个文本文件中读取,该文本文件在写入时有多个输出,但是当我想从我已经输出内容的文本文件中读取时,我想选择最后一个条目(记住写作时的每个条目都有 5 行,我只想要包含 "Ciphered text:")

的行

但是它正在读取包含它的行,但我不知道如何让它只显示包含我指定的字符串的最后一个条目。

using System;
using System.IO;

namespace ReadLastContain
{
    class StreamRead
    {
        static void Main(string[] args)
        {
            string TempFile = @"C:\Users\Josh\Desktop\text2.txt";
            using (var source = new StreamReader(TempFile))
            {
                string line;
                while ((line = source.ReadLine()) != null)
                {
                    if (line.Contains("Ciphered Text:"))
                    {
                        Console.WriteLine(line);
                    }
                }
            }
        }
    }
}

您可以使用 Linq:

var text = File
  .ReadLines(@"C:\Users\Josh\Desktop\text2.txt")
  .LastOrDefault(line => line.Contains("Ciphered Text:"));

if (null != text) // if there´s a text to print out
  Console.WriteLine(text);

我建议使用 LINQ 以获得更好的可读性:

string lastCipheredText = File.ReadLines(TempFile)
    .LastOrDefault(l => l.Contains("Ciphered Text:"));

如果没有这一行就是null。如果您不能使用 LINQ:

string lastCipheredText = null;
while ((line = source.ReadLine()) != null)
{
    if (line.Contains("Ciphered Text:"))
    {
        lastCipheredText = line;
    }
}

它将始终被覆盖,因此您会自动获取包含它的最后一行。