【问题标题】:StreamReader read last line that containsStreamReader 读取包含的最后一行
【发布时间】:2015-11-26 14:54:58
【问题描述】:

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

【问题讨论】:

  • 从头读取怎么样?
  • 你能在你的问题中添加文件的内容吗?

标签: c# streamreader


【解决方案1】:

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

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

【讨论】:

  • 谢谢蒂姆,太好了!并感谢您的快速回复:)
【解决方案2】:

你可以使用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);

【讨论】:

  • 谢谢 Dmitry 我用了 tim's 不过还是谢谢!
猜你喜欢
  • 2015-07-23
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
相关资源
最近更新 更多