C# StreamReader读取包含的最后一行
我试图从一个文本文件中读取内容,该文本文件在写入时有多个输出,但当我想从已经输出内容的文本文件中读取内容时,我想选择最后一个条目(请记住,写入时每个条目有5行,我只想要包含“加密文本:”的行) 但是它正在读取包含该字符串的行,但是我无法让它只显示包含我指定的字符串的最后一个条目C# StreamReader读取包含的最后一行,c#,streamreader,C#,Streamreader,我试图从一个文本文件中读取内容,该文本文件在写入时有多个输出,但当我想从已经输出内容的文本文件中读取内容时,我想选择最后一个条目(请记住,写入时每个条目有5行,我只想要包含“加密文本:”的行) 但是它正在读取包含该字符串的行,但是我无法让它只显示包含我指定的字符串的最后一个条目 using System; using System.IO; namespace ReadLastContain { class StreamRead { static void Mai
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:
我建议使用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;
}
}
它将始终被覆盖,因此您将自动获得包含它的最后一行。从末尾读取如何?您可以在问题中添加文件的内容。谢谢tim,太好了,它可以工作了!谢谢你的快速回复:)谢谢你,德米特里,虽然我用了蒂姆的,但还是谢谢你!
string lastCipheredText = null;
while ((line = source.ReadLine()) != null)
{
if (line.Contains("Ciphered Text:"))
{
lastCipheredText = line;
}
}