c# - StreamReader 读取包含的最后一行

标签 c# streamreader

我试图从一个文本文件中读取,该文本文件在写入时有多个输出,但是当我想从我已经输出内容的文本文件中读取时,我想选择最后一个条目(记住每个条目当写作有 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);
                    }
                }
            }
        }
    }
}

最佳答案

我建议使用 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;
    }
}

它总是会被覆盖,所以你会自动得到包含它的最后一行。

关于c# - StreamReader 读取包含的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33941592/

相关文章:

javascript - eventRender 未被触发 Fullcalendar ASP.net C# webforms

c# - 如何避免派生类中的向下转型

C# DPAPI 必须声明一个主体,因为它没有标记为抽象

c# - StreamReader 的内存泄漏(?)

.net - RichTextBox 不显示 ' 并显示一个菱形,而不是里面有一个问号

c# - 是否可以在 C# DataColumn.Expression 的 SUM 中使用 IIF?

c# - 如何在 C# 中修改 Access DB 的架构

c# - StreamReader 路径使用 * - 路径中的非法字符

C# XNA - 读取 .txt 文件并创建二维数组

c# - StreamReader ReadBlock 卡在二进制文件上