StreamReader读取包含的最后一行

本文关键字:一行 最后 读取 包含 StreamReader | 更新日期: 2023-09-27 18:24:29

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

但有了这个,它正在读取包含它的行,但我无法使它只显示包含我指定的字符串的最后一个条目。

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);
                    }
                }
            }
        }
    }
}

StreamReader读取包含的最后一行

为了更好的可读性,我建议使用LINQ:

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

如果没有这样的线路,则为CCD_ 1。如果你不能使用LINQ:

string lastCipheredText = null;
while ((line = source.ReadLine()) != null)
{
    if (line.Contains("Ciphered Text:"))
    {
        lastCipheredText = 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);