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